diff --git a/.gitmodules b/.gitmodules index c4175f6e86..91585f7b9a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,7 +3,7 @@ url = git://github.com/cocos2d/bindings-generator.git [submodule "cocos/scripting/auto-generated"] path = cocos/scripting/auto-generated -url=git://github.com/cocos2d-x/bindings-auto-generated.git + url = git://github.com/cocos2d-x/bindings-auto-generated.git [submodule "samples/Javascript/Shared"] path = samples/Javascript/Shared url = git://github.com/cocos2d/cocos2d-js-tests.git diff --git a/cocos2dx/base_nodes/CCNode.cpp b/cocos2dx/base_nodes/CCNode.cpp deleted file mode 100644 index 4c3168fde4..0000000000 --- a/cocos2dx/base_nodes/CCNode.cpp +++ /dev/null @@ -1,1538 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2009 Valentin Milea -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCNode.h" - -#include - -#include "cocoa/CCString.h" -#include "support/data_support/ccCArray.h" -#include "support/TransformUtils.h" -#include "CCCamera.h" -#include "effects/CCGrid.h" -#include "CCDirector.h" -#include "CCScheduler.h" -#include "event_dispatcher/CCTouch.h" -#include "actions/CCActionManager.h" -#include "script_support/CCScriptSupport.h" -#include "shaders/CCGLProgram.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "event_dispatcher/CCEvent.h" -#include "event_dispatcher/CCEventTouch.h" - -#ifdef CC_USE_PHYSICS -#include "physics/CCPhysicsBody.h" -#endif - -// externals -#include "kazmath/GL/matrix.h" -#include "support/component/CCComponent.h" -#include "support/component/CCComponentContainer.h" - - - -#if CC_NODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -NS_CC_BEGIN - -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2) -{ - Object *p1 = static_cast(pp1); - Object *p2 = static_cast(pp2); - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#else -bool nodeComparisonLess(Object* p1, Object* p2) -{ - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#endif - -// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. -static int s_globalOrderOfArrival = 1; -int Node::_globalEventPriorityIndex = 0; - -Node::Node(void) -: _rotationX(0.0f) -, _rotationY(0.0f) -, _scaleX(1.0f) -, _scaleY(1.0f) -, _vertexZ(0.0f) -, _position(Point::ZERO) -, _skewX(0.0f) -, _skewY(0.0f) -, _anchorPointInPoints(Point::ZERO) -, _anchorPoint(Point::ZERO) -, _contentSize(Size::ZERO) -, _additionalTransform(AffineTransform::IDENTITY) -, _transform(AffineTransform::IDENTITY) -, _inverse(AffineTransform::IDENTITY) -, _additionalTransformDirty(false) -, _transformDirty(true) -, _inverseDirty(true) -, _camera(NULL) -// children (lazy allocs) -// lazy alloc -, _grid(NULL) -, _ZOrder(0) -, _children(NULL) -, _parent(NULL) -// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true -, _tag(Node::INVALID_TAG) -// userData is always inited as nil -, _userData(NULL) -, _userObject(NULL) -, _shaderProgram(NULL) -, _orderOfArrival(0) -, _running(false) -, _visible(true) -, _ignoreAnchorPointForPosition(false) -, _reorderChildDirty(false) -, _isTransitionFinished(false) -, _updateScriptHandler(0) -, _componentContainer(NULL) -, _eventPriority(0) -, _oldEventPriority(0) -#ifdef CC_USE_PHYSICS -, _physicsBody(nullptr) -#endif -{ - // set default scheduler and actionManager - Director *director = Director::getInstance(); - _actionManager = director->getActionManager(); - _actionManager->retain(); - _scheduler = director->getScheduler(); - _scheduler->retain(); - - ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); - _scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone; -} - -Node::~Node() -{ - CCLOGINFO( "deallocing Node: %p - tag: %i", this, _tag ); - - if (_updateScriptHandler) - { - ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler); - } - - CC_SAFE_RELEASE(_actionManager); - CC_SAFE_RELEASE(_scheduler); - // attributes - CC_SAFE_RELEASE(_camera); - - CC_SAFE_RELEASE(_grid); - CC_SAFE_RELEASE(_shaderProgram); - CC_SAFE_RELEASE(_userObject); - - if(_children && _children->count() > 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* node = static_cast(child); - if (node) - { - node->_parent = NULL; - } - } - } - - // children - CC_SAFE_RELEASE(_children); - - removeAllComponents(); - - CC_SAFE_DELETE(_componentContainer); - - removeAllEventListeners(); - -#ifdef CC_USE_PHYSICS - CC_SAFE_RELEASE(_physicsBody); -#endif -} - -bool Node::init() -{ - return true; -} - -float Node::getSkewX() const -{ - return _skewX; -} - -void Node::setSkewX(float newSkewX) -{ - _skewX = newSkewX; - _transformDirty = _inverseDirty = true; -} - -float Node::getSkewY() const -{ - return _skewY; -} - -void Node::setSkewY(float newSkewY) -{ - _skewY = newSkewY; - - _transformDirty = _inverseDirty = true; -} - -/// zOrder getter -int Node::getZOrder() const -{ - return _ZOrder; -} - -/// zOrder setter : private method -/// used internally to alter the zOrder variable. DON'T call this method manually -void Node::_setZOrder(int z) -{ - _ZOrder = z; -} - -void Node::setZOrder(int z) -{ - _setZOrder(z); - if (_parent) - { - _parent->reorderChild(this, z); - } -} - -/// vertexZ getter -float Node::getVertexZ() const -{ - return _vertexZ; -} - - -/// vertexZ setter -void Node::setVertexZ(float var) -{ - _vertexZ = var; -} - - -/// rotation getter -float Node::getRotation() const -{ - CCASSERT(_rotationX == _rotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return"); - return _rotationX; -} - -/// rotation setter -void Node::setRotation(float newRotation) -{ - _rotationX = _rotationY = newRotation; - _transformDirty = _inverseDirty = true; - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setRotation(newRotation); - } -#endif -} - -float Node::getRotationX() const -{ - return _rotationX; -} - -void Node::setRotationX(float fRotationX) -{ - _rotationX = fRotationX; - _transformDirty = _inverseDirty = true; -} - -float Node::getRotationY() const -{ - return _rotationY; -} - -void Node::setRotationY(float fRotationY) -{ - _rotationY = fRotationY; - _transformDirty = _inverseDirty = true; -} - -/// scale getter -float Node::getScale(void) const -{ - CCASSERT( _scaleX == _scaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return"); - return _scaleX; -} - -/// scale setter -void Node::setScale(float scale) -{ - _scaleX = _scaleY = scale; - _transformDirty = _inverseDirty = true; -} - -/// scaleX getter -float Node::getScaleX() const -{ - return _scaleX; -} - -/// scale setter -void Node::setScale(float scaleX,float scaleY) -{ - _scaleX = scaleX; - _scaleY = scaleY; - _transformDirty = _inverseDirty = true; -} - -/// scaleX setter -void Node::setScaleX(float newScaleX) -{ - _scaleX = newScaleX; - _transformDirty = _inverseDirty = true; -} - -/// scaleY getter -float Node::getScaleY() const -{ - return _scaleY; -} - -/// scaleY setter -void Node::setScaleY(float newScaleY) -{ - _scaleY = newScaleY; - _transformDirty = _inverseDirty = true; -} - -/// position getter -const Point& Node::getPosition() const -{ - return _position; -} - -/// position setter -void Node::setPosition(const Point& newPosition) -{ - _position = newPosition; - _transformDirty = _inverseDirty = true; - -#ifdef CC_USE_PHYSICS - if (_physicsBody) - { - _physicsBody->setPosition(newPosition); - } -#endif -} - -void Node::getPosition(float* x, float* y) const -{ - *x = _position.x; - *y = _position.y; -} - -void Node::setPosition(float x, float y) -{ - setPosition(Point(x, y)); -} - -float Node::getPositionX() const -{ - return _position.x; -} - -float Node::getPositionY() const -{ - return _position.y; -} - -void Node::setPositionX(float x) -{ - setPosition(Point(x, _position.y)); -} - -void Node::setPositionY(float y) -{ - setPosition(Point(_position.x, y)); -} - -unsigned int Node::getChildrenCount() const -{ - return _children ? _children->count() : 0; -} - -/// camera getter: lazy alloc -Camera* Node::getCamera() -{ - if (!_camera) - { - _camera = new Camera(); - } - - return _camera; -} - -/// grid setter -void Node::setGrid(GridBase* pGrid) -{ - CC_SAFE_RETAIN(pGrid); - CC_SAFE_RELEASE(_grid); - _grid = pGrid; -} - - -/// isVisible getter -bool Node::isVisible() const -{ - return _visible; -} - -/// isVisible setter -void Node::setVisible(bool var) -{ - _visible = var; -} - -const Point& Node::getAnchorPointInPoints() const -{ - return _anchorPointInPoints; -} - -/// anchorPoint getter -const Point& Node::getAnchorPoint() const -{ - return _anchorPoint; -} - -void Node::setAnchorPoint(const Point& point) -{ - if( ! point.equals(_anchorPoint)) - { - _anchorPoint = point; - _anchorPointInPoints = Point(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y ); - _transformDirty = _inverseDirty = true; - } -} - -/// contentSize getter -const Size& Node::getContentSize() const -{ - return _contentSize; -} - -void Node::setContentSize(const Size & size) -{ - if ( ! size.equals(_contentSize)) - { - _contentSize = size; - - _anchorPointInPoints = Point(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y ); - _transformDirty = _inverseDirty = true; - } -} - -// isRunning getter -bool Node::isRunning() const -{ - return _running; -} - -/// parent setter -void Node::setParent(Node * var) -{ - _parent = var; -} - -/// isRelativeAnchorPoint getter -bool Node::isIgnoreAnchorPointForPosition() const -{ - return _ignoreAnchorPointForPosition; -} -/// isRelativeAnchorPoint setter -void Node::ignoreAnchorPointForPosition(bool newValue) -{ - if (newValue != _ignoreAnchorPointForPosition) - { - _ignoreAnchorPointForPosition = newValue; - _transformDirty = _inverseDirty = true; - } -} - -/// tag getter -int Node::getTag() const -{ - return _tag; -} - -/// tag setter -void Node::setTag(int var) -{ - _tag = var; -} - -/// userData setter -void Node::setUserData(void *var) -{ - _userData = var; -} - -int Node::getOrderOfArrival() const -{ - return _orderOfArrival; -} - -void Node::setOrderOfArrival(int orderOfArrival) -{ - CCASSERT(orderOfArrival >=0, "Invalid orderOfArrival"); - _orderOfArrival = orderOfArrival; -} - -void Node::setUserObject(Object *pUserObject) -{ - CC_SAFE_RETAIN(pUserObject); - CC_SAFE_RELEASE(_userObject); - _userObject = pUserObject; -} - -void Node::setShaderProgram(GLProgram *pShaderProgram) -{ - CC_SAFE_RETAIN(pShaderProgram); - CC_SAFE_RELEASE(_shaderProgram); - _shaderProgram = pShaderProgram; -} - -Rect Node::getBoundingBox() const -{ - Rect rect = Rect(0, 0, _contentSize.width, _contentSize.height); - return RectApplyAffineTransform(rect, getNodeToParentTransform()); -} - -Node * Node::create(void) -{ - Node * pRet = new Node(); - if (pRet && pRet->init()) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - return pRet; -} - -void Node::cleanup() -{ - // actions - this->stopAllActions(); - this->unscheduleAllSelectors(); - - if ( _scriptType != kScriptTypeNone) - { - int action = kNodeOnCleanup; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } - - // timers - arrayMakeObjectsPerformSelector(_children, cleanup, Node*); -} - - -const char* Node::description() const -{ - return String::createWithFormat("", _tag)->getCString(); -} - -// lazy allocs -void Node::childrenAlloc(void) -{ - _children = Array::createWithCapacity(4); - _children->retain(); -} - -Node* Node::getChildByTag(int aTag) -{ - CCASSERT( aTag != Node::INVALID_TAG, "Invalid tag"); - - if(_children && _children->count() > 0) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = static_cast(child); - if(pNode && pNode->_tag == aTag) - return pNode; - } - } - return NULL; -} - -/* "add" logic MUST only be on this method -* If a class want's to extend the 'addChild' behavior it only needs -* to override this method -*/ -void Node::addChild(Node *child, int zOrder, int tag) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - CCASSERT( child->_parent == NULL, "child already added. It can't be added again"); - - if( ! _children ) - { - this->childrenAlloc(); - } - - this->insertChild(child, zOrder); - - child->_tag = tag; - - child->setParent(this); - child->setOrderOfArrival(s_globalOrderOfArrival++); - - if( _running ) - { - child->onEnter(); - // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter - if (_isTransitionFinished) { - child->onEnterTransitionDidFinish(); - } - } -} - -void Node::addChild(Node *child, int zOrder) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - this->addChild(child, zOrder, child->_tag); -} - -void Node::addChild(Node *child) -{ - CCASSERT( child != NULL, "Argument must be non-nil"); - this->addChild(child, child->_ZOrder, child->_tag); -} - -void Node::removeFromParent() -{ - this->removeFromParentAndCleanup(true); -} - -void Node::removeFromParentAndCleanup(bool cleanup) -{ - if (_parent != NULL) - { - _parent->removeChild(this,cleanup); - } -} - -/* "remove" logic MUST only be on this method -* If a class want's to extend the 'removeChild' behavior it only needs -* to override this method -*/ -void Node::removeChild(Node* child, bool cleanup /* = true */) -{ - // explicit nil handling - if (_children == NULL) - { - return; - } - - int index = _children->getIndexOfObject(child); - if( index != CC_INVALID_INDEX ) - this->detachChild( child, index, cleanup ); -} - -void Node::removeChildByTag(int tag, bool cleanup/* = true */) -{ - CCASSERT( tag != Node::INVALID_TAG, "Invalid tag"); - - Node *child = this->getChildByTag(tag); - - if (child == NULL) - { - CCLOG("cocos2d: removeChildByTag(tag = %d): child not found!", tag); - } - else - { - this->removeChild(child, cleanup); - } -} - -void Node::removeAllChildren() -{ - this->removeAllChildrenWithCleanup(true); -} - -void Node::removeAllChildrenWithCleanup(bool cleanup) -{ - // not using detachChild improves speed here - if ( _children && _children->count() > 0 ) - { - Object* child; - CCARRAY_FOREACH(_children, child) - { - Node* pNode = static_cast(child); - if (pNode) - { - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if(_running) - { - pNode->onExitTransitionDidStart(); - pNode->onExit(); - } - - if (cleanup) - { - pNode->cleanup(); - } - // set parent nil at the end - pNode->setParent(NULL); - } - } - - _children->removeAllObjects(); - } - -} - -void Node::detachChild(Node *child, int childIndex, bool doCleanup) -{ - // IMPORTANT: - // -1st do onExit - // -2nd cleanup - if (_running) - { - child->onExitTransitionDidStart(); - child->onExit(); - } - - // If you don't do cleanup, the child's actions will not get removed and the - // its scheduledSelectors_ dict will not get released! - if (doCleanup) - { - child->cleanup(); - } - - // set parent nil at the end - child->setParent(NULL); - - _children->removeObjectAtIndex(childIndex); -} - - -// helper used by reorderChild & add -void Node::insertChild(Node* child, int z) -{ - _reorderChildDirty = true; - _children->addObject(child); - child->_setZOrder(z); -} - -void Node::reorderChild(Node *child, int zOrder) -{ - CCASSERT( child != NULL, "Child must be non-nil"); - _reorderChildDirty = true; - child->setOrderOfArrival(s_globalOrderOfArrival++); - child->_setZOrder(zOrder); -} - -void Node::sortAllChildren() -{ -#if 0 - if (_reorderChildDirty) - { - int i,j,length = _children->count(); - - // insertion sort - for(i=1; i( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->_ZOrder < tempJ->_ZOrder || ( tempI->_ZOrder == tempJ->_ZOrder && tempI->_orderOfArrival < tempJ->_orderOfArrival ) ) ) - { - _children->fastSetObject( tempJ, j+1 ); - j = j-1; - if(j>=0) - tempJ = static_cast( _children->getObjectAtIndex(j) ); - } - _children->fastSetObject(tempI, j+1); - } - - //don't need to check children recursively, that's done in visit of each child - - _reorderChildDirty = false; - } -#else - if( _reorderChildDirty ) { - std::sort( std::begin(*_children), std::end(*_children), nodeComparisonLess ); - _reorderChildDirty = false; - } -#endif -} - - - void Node::draw() - { - //CCASSERT(0); - // override me - // Only use- this function to draw your stuff. - // DON'T draw your stuff outside this method - } - -void Node::visit() -{ - // quick return if not visible. children won't be drawn. - if (!_visible) - { - return; - } - - kmGLPushMatrix(); - - if (_grid && _grid->isActive()) - { - _grid->beforeDraw(); - } - - this->transform(); - int i = 0; - - if(_children && _children->count() > 0) - { - sortAllChildren(); - // draw children zOrder < 0 - for( ; i < _children->count(); i++ ) - { - auto node = static_cast( _children->getObjectAtIndex(i) ); - - if ( node && node->_ZOrder < 0 ) - node->visit(); - else - break; - } - // self draw - this->draw(); - updateEventPriorityIndex(); - - for( ; i < _children->count(); i++ ) - { - auto node = static_cast( _children->getObjectAtIndex(i) ); - if (node) - node->visit(); - } - } - else - { - this->draw(); - updateEventPriorityIndex(); - } - - // reset for next frame - _orderOfArrival = 0; - - if (_grid && _grid->isActive()) - { - _grid->afterDraw(this); - } - - kmGLPopMatrix(); -} - -void Node::transformAncestors() -{ - if( _parent != NULL ) - { - _parent->transformAncestors(); - _parent->transform(); - } -} - -#ifdef CC_USE_PHYSICS -void Node::updatePhysicsTransform() -{ - if (_physicsBody && _physicsBody->isEnable() && !_physicsBody->isResting()) - { - _position = _physicsBody->getPosition(); - _rotationX = _rotationY = _physicsBody->getRotation(); - _transformDirty = _inverseDirty = true; - } -} -#endif - - -void Node::transform() -{ -#ifdef CC_USE_PHYSICS - updatePhysicsTransform(); -#endif - - kmMat4 transfrom4x4; - - // Convert 3x3 into 4x4 matrix - CGAffineToGL(this->getNodeToParentTransform(), transfrom4x4.mat); - - // Update Z vertex manually - transfrom4x4.mat[14] = _vertexZ; - - kmGLMultMatrix( &transfrom4x4 ); - - - // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if ( _camera != NULL && !(_grid != NULL && _grid->isActive()) ) - { - bool translate = (_anchorPointInPoints.x != 0.0f || _anchorPointInPoints.y != 0.0f); - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(_anchorPointInPoints.y), 0 ); - - _camera->locate(); - - if( translate ) - kmGLTranslatef(RENDER_IN_SUBPIXEL(-_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(-_anchorPointInPoints.y), 0 ); - } - -} - - -void Node::onEnter() -{ - _isTransitionFinished = false; - - arrayMakeObjectsPerformSelector(_children, onEnter, Node*); - - this->resumeSchedulerAndActions(); - - _running = true; - - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnEnter; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onEnterTransitionDidFinish() -{ - _isTransitionFinished = true; - - arrayMakeObjectsPerformSelector(_children, onEnterTransitionDidFinish, Node*); - - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnEnterTransitionDidFinish; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onExitTransitionDidStart() -{ - arrayMakeObjectsPerformSelector(_children, onExitTransitionDidStart, Node*); - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnExitTransitionDidStart; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } -} - -void Node::onExit() -{ - this->pauseSchedulerAndActions(); - - _running = false; - if (_scriptType != kScriptTypeNone) - { - int action = kNodeOnExit; - BasicScriptData data(this,(void*)&action); - ScriptEvent scriptEvent(kNodeEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent); - } - - arrayMakeObjectsPerformSelector(_children, onExit, Node*); - - removeAllEventListeners(); -} - -void Node::setActionManager(ActionManager* actionManager) -{ - if( actionManager != _actionManager ) { - this->stopAllActions(); - CC_SAFE_RETAIN(actionManager); - CC_SAFE_RELEASE(_actionManager); - _actionManager = actionManager; - } -} - -Action * Node::runAction(Action* action) -{ - CCASSERT( action != NULL, "Argument must be non-nil"); - _actionManager->addAction(action, this, !_running); - return action; -} - -void Node::stopAllActions() -{ - _actionManager->removeAllActionsFromTarget(this); -} - -void Node::stopAction(Action* action) -{ - _actionManager->removeAction(action); -} - -void Node::stopActionByTag(int tag) -{ - CCASSERT( tag != Action::INVALID_TAG, "Invalid tag"); - _actionManager->removeActionByTag(tag, this); -} - -Action * Node::getActionByTag(int tag) -{ - CCASSERT( tag != Action::INVALID_TAG, "Invalid tag"); - return _actionManager->getActionByTag(tag, this); -} - -unsigned int Node::getNumberOfRunningActions() const -{ - return _actionManager->getNumberOfRunningActionsInTarget(this); -} - -// Node - Callbacks - -void Node::setScheduler(Scheduler* scheduler) -{ - if( scheduler != _scheduler ) { - this->unscheduleAllSelectors(); - CC_SAFE_RETAIN(scheduler); - CC_SAFE_RELEASE(_scheduler); - _scheduler = scheduler; - } -} - -bool Node::isScheduled(SEL_SCHEDULE selector) -{ - return _scheduler->isScheduledForTarget(selector, this); -} - -void Node::scheduleUpdate() -{ - scheduleUpdateWithPriority(0); -} - -void Node::scheduleUpdateWithPriority(int priority) -{ - _scheduler->scheduleUpdateForTarget(this, priority, !_running); -} - -void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) -{ - unscheduleUpdate(); - _updateScriptHandler = nHandler; - _scheduler->scheduleUpdateForTarget(this, priority, !_running); -} - -void Node::unscheduleUpdate() -{ - _scheduler->unscheduleUpdateForTarget(this); - if (_updateScriptHandler) - { - ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_updateScriptHandler); - _updateScriptHandler = 0; - } -} - -void Node::schedule(SEL_SCHEDULE selector) -{ - this->schedule(selector, 0.0f, kRepeatForever, 0.0f); -} - -void Node::schedule(SEL_SCHEDULE selector, float interval) -{ - this->schedule(selector, interval, kRepeatForever, 0.0f); -} - -void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) -{ - CCASSERT( selector, "Argument must be non-nil"); - CCASSERT( interval >=0, "Argument must be positive"); - - _scheduler->scheduleSelector(selector, this, interval , repeat, delay, !_running); -} - -void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) -{ - this->schedule(selector, 0.0f, 0, delay); -} - -void Node::unschedule(SEL_SCHEDULE selector) -{ - // explicit nil handling - if (selector == 0) - return; - - _scheduler->unscheduleSelector(selector, this); -} - -void Node::unscheduleAllSelectors() -{ - _scheduler->unscheduleAllForTarget(this); -} - -void Node::resumeSchedulerAndActions() -{ - _scheduler->resumeTarget(this); - _actionManager->resumeTarget(this); -} - -void Node::pauseSchedulerAndActions() -{ - _scheduler->pauseTarget(this); - _actionManager->pauseTarget(this); -} - -// override me -void Node::update(float fDelta) -{ - if (0 != _updateScriptHandler) - { - //only lua use - SchedulerScriptData data(_updateScriptHandler,fDelta); - ScriptEvent event(kScheduleEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } - - if (_componentContainer && !_componentContainer->isEmpty()) - { - _componentContainer->visit(fDelta); - } -} - -const AffineTransform& Node::getNodeToParentTransform() const -{ - if (_transformDirty) - { - - // Translate values - float x = _position.x; - float y = _position.y; - - if (_ignoreAnchorPointForPosition) - { - x += _anchorPointInPoints.x; - y += _anchorPointInPoints.y; - } - - // Rotation values - // Change rotation code to handle X and Y - // If we skew with the exact same value for both x and y then we're simply just rotating - float cx = 1, sx = 0, cy = 1, sy = 0; - if (_rotationX || _rotationY) - { - float radiansX = -CC_DEGREES_TO_RADIANS(_rotationX); - float radiansY = -CC_DEGREES_TO_RADIANS(_rotationY); - cx = cosf(radiansX); - sx = sinf(radiansX); - cy = cosf(radiansY); - sy = sinf(radiansY); - } - - bool needsSkewMatrix = ( _skewX || _skewY ); - - - // optimization: - // inline anchor point calculation if skew is not needed - // Adjusted transform calculation for rotational skew - if (! needsSkewMatrix && !_anchorPointInPoints.equals(Point::ZERO)) - { - x += cy * -_anchorPointInPoints.x * _scaleX + -sx * -_anchorPointInPoints.y * _scaleY; - y += sy * -_anchorPointInPoints.x * _scaleX + cx * -_anchorPointInPoints.y * _scaleY; - } - - - // Build Transform Matrix - // Adjusted transform calculation for rotational skew - _transform = AffineTransformMake( cy * _scaleX, sy * _scaleX, - -sx * _scaleY, cx * _scaleY, - x, y ); - - // XXX: Try to inline skew - // If skew is needed, apply skew and then anchor point - if (needsSkewMatrix) - { - AffineTransform skewMatrix = AffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(_skewY)), - tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1.0f, - 0.0f, 0.0f ); - _transform = AffineTransformConcat(skewMatrix, _transform); - - // adjust anchor point - if (!_anchorPointInPoints.equals(Point::ZERO)) - { - _transform = AffineTransformTranslate(_transform, -_anchorPointInPoints.x, -_anchorPointInPoints.y); - } - } - - if (_additionalTransformDirty) - { - _transform = AffineTransformConcat(_transform, _additionalTransform); - _additionalTransformDirty = false; - } - - _transformDirty = false; - } - - return _transform; -} - -void Node::setAdditionalTransform(const AffineTransform& additionalTransform) -{ - _additionalTransform = additionalTransform; - _transformDirty = true; - _additionalTransformDirty = true; -} - -const AffineTransform& Node::getParentToNodeTransform() const -{ - if ( _inverseDirty ) { - _inverse = AffineTransformInvert(this->getNodeToParentTransform()); - _inverseDirty = false; - } - - return _inverse; -} - -AffineTransform Node::getNodeToWorldTransform() const -{ - AffineTransform t = this->getNodeToParentTransform(); - - for (Node *p = _parent; p != NULL; p = p->getParent()) - t = AffineTransformConcat(t, p->getNodeToParentTransform()); - - return t; -} - -AffineTransform Node::getWorldToNodeTransform() const -{ - return AffineTransformInvert(this->getNodeToWorldTransform()); -} - -Point Node::convertToNodeSpace(const Point& worldPoint) const -{ - Point ret = PointApplyAffineTransform(worldPoint, getWorldToNodeTransform()); - return ret; -} - -Point Node::convertToWorldSpace(const Point& nodePoint) const -{ - Point ret = PointApplyAffineTransform(nodePoint, getNodeToWorldTransform()); - return ret; -} - -Point Node::convertToNodeSpaceAR(const Point& worldPoint) const -{ - Point nodePoint = convertToNodeSpace(worldPoint); - return nodePoint - _anchorPointInPoints; -} - -Point Node::convertToWorldSpaceAR(const Point& nodePoint) const -{ - Point pt = nodePoint + _anchorPointInPoints; - return convertToWorldSpace(pt); -} - -Point Node::convertToWindowSpace(const Point& nodePoint) const -{ - Point worldPoint = this->convertToWorldSpace(nodePoint); - return Director::getInstance()->convertToUI(worldPoint); -} - -// convenience methods which take a Touch instead of Point -Point Node::convertTouchToNodeSpace(Touch *touch) const -{ - Point point = touch->getLocation(); - return this->convertToNodeSpace(point); -} -Point Node::convertTouchToNodeSpaceAR(Touch *touch) const -{ - Point point = touch->getLocation(); - return this->convertToNodeSpaceAR(point); -} - -void Node::updateTransform() -{ - // Recursively iterate over children - arrayMakeObjectsPerformSelector(_children, updateTransform, Node*); -} - -Component* Node::getComponent(const char *pName) -{ - if( _componentContainer ) - return _componentContainer->get(pName); - return nullptr; -} - -bool Node::addComponent(Component *pComponent) -{ - // lazy alloc - if( !_componentContainer ) - _componentContainer = new ComponentContainer(this); - return _componentContainer->add(pComponent); -} - -bool Node::removeComponent(const char *pName) -{ - if( _componentContainer ) - return _componentContainer->remove(pName); - return false; -} - -void Node::removeAllComponents() -{ - if( _componentContainer ) - _componentContainer->removeAll(); -} - -void Node::resetEventPriorityIndex() -{ - _globalEventPriorityIndex = 0; -} - -void Node::associateEventListener(EventListener* listener) -{ - _eventlisteners.insert(listener); -} - -void Node::dissociateEventListener(EventListener* listener) -{ - _eventlisteners.erase(listener); -} - -void Node::removeAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - auto eventListenersCopy = _eventlisteners; - - for (auto& listener : eventListenersCopy) - { - dispatcher->removeEventListener(listener); - } -} - -void Node::setDirtyForAllEventListeners() -{ - auto dispatcher = EventDispatcher::getInstance(); - - for (auto& listener : _eventlisteners) - { - dispatcher->setDirtyForEventType(listener->_type, true); - } -} - -#ifdef CC_USE_PHYSICS -void Node::setPhysicsBody(PhysicsBody* body) -{ - if (_physicsBody != nullptr) - { - _physicsBody->release(); - } - - _physicsBody = body; - _physicsBody->retain(); - _physicsBody->setPosition(getPosition()); - _physicsBody->setRotation(getRotation()); -} - -PhysicsBody* Node::getPhysicsBody() const -{ - return _physicsBody; -} -#endif //CC_USE_PHYSICS - -// NodeRGBA -NodeRGBA::NodeRGBA() -: _displayedOpacity(255) -, _realOpacity(255) -, _displayedColor(Color3B::WHITE) -, _realColor(Color3B::WHITE) -, _cascadeColorEnabled(false) -, _cascadeOpacityEnabled(false) -{} - -NodeRGBA::~NodeRGBA() {} - -bool NodeRGBA::init() -{ - if (Node::init()) - { - _displayedOpacity = _realOpacity = 255; - _displayedColor = _realColor = Color3B::WHITE; - _cascadeOpacityEnabled = _cascadeColorEnabled = false; - return true; - } - return false; -} - -GLubyte NodeRGBA::getOpacity(void) const -{ - return _realOpacity; -} - -GLubyte NodeRGBA::getDisplayedOpacity(void) const -{ - return _displayedOpacity; -} - -void NodeRGBA::setOpacity(GLubyte opacity) -{ - _displayedOpacity = _realOpacity = opacity; - - if (_cascadeOpacityEnabled) - { - GLubyte parentOpacity = 255; - RGBAProtocol* pParent = dynamic_cast(_parent); - if (pParent && pParent->isCascadeOpacityEnabled()) - { - parentOpacity = pParent->getDisplayedOpacity(); - } - this->updateDisplayedOpacity(parentOpacity); - } -} - -void NodeRGBA::updateDisplayedOpacity(GLubyte parentOpacity) -{ - _displayedOpacity = _realOpacity * parentOpacity/255.0; - - if (_cascadeOpacityEnabled) - { - Object* pObj; - CCARRAY_FOREACH(_children, pObj) - { - RGBAProtocol* item = dynamic_cast(pObj); - if (item) - { - item->updateDisplayedOpacity(_displayedOpacity); - } - } - } -} - -bool NodeRGBA::isCascadeOpacityEnabled(void) const -{ - return _cascadeOpacityEnabled; -} - -void NodeRGBA::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) -{ - _cascadeOpacityEnabled = cascadeOpacityEnabled; -} - -const Color3B& NodeRGBA::getColor(void) const -{ - return _realColor; -} - -const Color3B& NodeRGBA::getDisplayedColor() const -{ - return _displayedColor; -} - -void NodeRGBA::setColor(const Color3B& color) -{ - _displayedColor = _realColor = color; - - if (_cascadeColorEnabled) - { - Color3B parentColor = Color3B::WHITE; - RGBAProtocol *parent = dynamic_cast(_parent); - if (parent && parent->isCascadeColorEnabled()) - { - parentColor = parent->getDisplayedColor(); - } - - updateDisplayedColor(parentColor); - } -} - -void NodeRGBA::updateDisplayedColor(const Color3B& parentColor) -{ - _displayedColor.r = _realColor.r * parentColor.r/255.0; - _displayedColor.g = _realColor.g * parentColor.g/255.0; - _displayedColor.b = _realColor.b * parentColor.b/255.0; - - if (_cascadeColorEnabled) - { - Object *obj = NULL; - CCARRAY_FOREACH(_children, obj) - { - RGBAProtocol *item = dynamic_cast(obj); - if (item) - { - item->updateDisplayedColor(_displayedColor); - } - } - } -} - -bool NodeRGBA::isCascadeColorEnabled(void) const -{ - return _cascadeColorEnabled; -} - -void NodeRGBA::setCascadeColorEnabled(bool cascadeColorEnabled) -{ - _cascadeColorEnabled = cascadeColorEnabled; -} - -NS_CC_END diff --git a/cocos2dx/base_nodes/CCNode.h b/cocos2dx/base_nodes/CCNode.h deleted file mode 100644 index 575e4b5cfb..0000000000 --- a/cocos2dx/base_nodes/CCNode.h +++ /dev/null @@ -1,1575 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2009 Valentin Milea - Copyright (c) 2011 Zynga Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __PLATFORM_CCNODE_H__ -#define __PLATFORM_CCNODE_H__ - -#include "ccMacros.h" -#include "cocoa/CCAffineTransform.h" -#include "cocoa/CCArray.h" -#include "CCGL.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "kazmath/kazmath.h" -#include "script_support/CCScriptSupport.h" -#include "CCProtocols.h" -#include "event_dispatcher/CCEventDispatcher.h" -#include "physics/CCPhysicsSetting.h" - -#include - -NS_CC_BEGIN - -class Camera; -class GridBase; -class Point; -class Touch; -class Action; -class RGBAProtocol; -class LabelProtocol; -class Scheduler; -class ActionManager; -class Component; -class Dictionary; -class ComponentContainer; -class EventDispatcher; -#ifdef CC_USE_PHYSICS -class PhysicsBody; -#endif - -/** - * @addtogroup base_nodes - * @{ - */ - -enum { - kNodeOnEnter, - kNodeOnExit, - kNodeOnEnterTransitionDidFinish, - kNodeOnExitTransitionDidStart, - kNodeOnCleanup -}; - -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2); -#else -bool nodeComparisonLess(Object* p1, Object* p2); -#endif - -class EventListener; - -/** @brief Node is the main element. Anything that gets drawn or contains things that get drawn is a Node. - The most popular Nodes are: Scene, Layer, Sprite, Menu. - - The main features of a Node are: - - They can contain other Node nodes (addChild, getChildByTag, removeChild, etc) - - They can schedule periodic callback (schedule, unschedule, etc) - - They can execute actions (runAction, stopAction, etc) - - Some Node nodes provide extra functionality for them or their children. - - Subclassing a Node usually means (one/all) of: - - overriding init to initialize resources and schedule callbacks - - create callbacks to handle the advancement of time - - overriding draw to render the node - - Features of Node: - - position - - scale (x, y) - - rotation (in degrees, clockwise) - - Camera (an interface to gluLookAt ) - - GridBase (to do mesh transformations) - - anchor point - - size - - visible - - z-order - - openGL z position - - Default values: - - rotation: 0 - - position: (x=0,y=0) - - scale: (x=1,y=1) - - contentSize: (x=0,y=0) - - anchorPoint: (x=0,y=0) - - Limitations: - - A Node is a "void" object. It doesn't have a texture - - Order in transformations with grid disabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be scaled (scale) - -# The node will be moved according to the camera values (camera) - - Order in transformations with grid enabled - -# The node will be translated (position) - -# The node will be rotated (rotation) - -# The node will be scaled (scale) - -# The grid will capture the screen - -# The node will be moved according to the camera values (camera) - -# The grid will render the captured screen - - Camera: - - Each node has a camera. By default it points to the center of the Node. - */ - -class CC_DLL Node : public Object -{ -public: - /// Default tag used for all the nodes - static const int INVALID_TAG = -1; - - /// @{ - /// @name Constructor, Destructor and Initializers - - /** - * Allocates and initializes a node. - * @return A initialized node which is marked as "autorelease". - */ - static Node * create(void); - - /** - * Default constructor - * @js ctor - */ - Node(void); - - /** - * Default destructor - * @js NA - * @lua NA - */ - virtual ~Node(void); - - /** - * Initializes the instance of Node - * @return Whether the initialization was successful. - */ - virtual bool init(); - - /** - * Gets the description string. It makes debugging easier. - * @return A string terminated with '\0' - * @js NA - * @lua NA - */ - const char* description(void) const; - - /// @} end of initializers - - - - /// @{ - /// @name Setters & Getters for Graphic Peroperties - - /** - * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. - * - * The Z order of node is relative to its "brothers": children of the same parent. - * It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d. - * The larger number it is, the later this node will be drawn in each message loop. - * Please refer to setVertexZ(float) for the difference. - * - * @param zOrder Z order of this node. - */ - virtual void setZOrder(int zOrder); - /** - * Sets the z order which stands for the drawing order - * - * This is an internal method. Don't call it outside the framework. - * The difference between setZOrder(int) and _setOrder(int) is: - * - _setZOrder(int) is a pure setter for _ZOrder memeber variable - * - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array. - */ - virtual void _setZOrder(int z); - /** - * Gets the Z order of this node. - * - * @see setZOrder(int) - * - * @return The Z order. - */ - virtual int getZOrder() const; - - /** - * Sets the real OpenGL Z vertex. - * - * Differences between openGL Z vertex and cocos2d Z order: - * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - * - OpenGL Z might require to set 2D projection - * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0 - * - * @warning Use it at your own risk since it might break the cocos2d parent-children z order - * - * @param vertexZ OpenGL Z vertex of this node. - */ - virtual void setVertexZ(float vertexZ); - /** - * Gets OpenGL Z vertex of this node. - * - * @see setVertexZ(float) - * - * @return OpenGL Z vertex of this node - */ - virtual float getVertexZ() const; - - - /** - * Changes the scale factor on X axis of this node - * - * The deafult value is 1.0 if you haven't changed it before - * - * @param scaleX The scale factor on X axis. - */ - virtual void setScaleX(float scaleX); - /** - * Returns the scale factor on X axis of this node - * - * @see setScaleX(float) - * - * @return The scale factor on X axis. - */ - virtual float getScaleX() const; - - - /** - * Changes the scale factor on Y axis of this node - * - * The Default value is 1.0 if you haven't changed it before. - * - * @param scaleY The scale factor on Y axis. - */ - virtual void setScaleY(float scaleY); - /** - * Returns the scale factor on Y axis of this node - * - * @see setScaleY(float) - * - * @return The scale factor on Y axis. - */ - virtual float getScaleY() const; - - - /** - * Changes both X and Y scale factor of the node. - * - * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. - * - * @param scale The scale factor for both X and Y axis. - */ - virtual void setScale(float scale); - /** - * Gets the scale factor of the node, when X and Y have the same scale factor. - * - * @warning Assert when _scaleX != _scaleY. - * @see setScale(float) - * - * @return The scale factor of the node. - */ - virtual float getScale() const; - - /** - * Changes both X and Y scale factor of the node. - * - * 1.0 is the default scale factor. It modifies the X and Y scale at the same time. - * - * @param scaleX The scale factor on X axis. - * @param scaleY The scale factor on Y axis. - */ - virtual void setScale(float scaleX,float scaleY); - - /** - * Changes the position (x,y) of the node in OpenGL coordinates - * - * Usually we use Point(x,y) to compose Point object. - * The original point (0,0) is at the left-bottom corner of screen. - * For example, this codesnip sets the node in the center of screen. - * @code - * Size size = Director::getInstance()->getWinSize(); - * node->setPosition( Point(size.width/2, size.height/2) ) - * @endcode - * - * @param position The position (x,y) of the node in OpenGL coordinates - */ - virtual void setPosition(const Point &position); - /** - * Gets the position (x,y) of the node in OpenGL coordinates - * - * @see setPosition(const Point&) - * - * @return The position (x,y) of the node in OpenGL coordinates - * @code - * In js and lua return value is table which contains x,y - * @endcode - */ - virtual const Point& getPosition() const; - /** - * Sets position in a more efficient way. - * - * Passing two numbers (x,y) is much efficient than passing Point object. - * This method is binded to lua and javascript. - * Passing a number is 10 times faster than passing a object from lua to c++ - * - * @code - * // sample code in lua - * local pos = node::getPosition() -- returns Point object from C++ - * node:setPosition(x, y) -- pass x, y coordinate to C++ - * @endcode - * - * @param x X coordinate for position - * @param y Y coordinate for position - */ - virtual void setPosition(float x, float y); - /** - * Gets position in a more efficient way, returns two number instead of a Point object - * - * @see setPosition(float, float) - * @code - * In js,out value not return - * @endcode - */ - virtual void getPosition(float* x, float* y) const; - /** - * Gets/Sets x or y coordinate individually for position. - * These methods are used in Lua and Javascript Bindings - */ - virtual void setPositionX(float x); - virtual float getPositionX(void) const; - virtual void setPositionY(float y); - virtual float getPositionY(void) const; - - - /** - * Changes the X skew angle of the node in degrees. - * - * This angle describes the shear distortion in the X direction. - * Thus, it is the angle between the Y axis and the left edge of the shape - * The default skewX angle is 0. Positive values distort the node in a CW direction. - * - * @param fSkewX The X skew angle of the node in degrees. - */ - virtual void setSkewX(float fSkewX); - /** - * Returns the X skew angle of the node in degrees. - * - * @see setSkewX(float) - * - * @return The X skew angle of the node in degrees. - */ - virtual float getSkewX() const; - - - /** - * Changes the Y skew angle of the node in degrees. - * - * This angle describes the shear distortion in the Y direction. - * Thus, it is the angle between the X axis and the bottom edge of the shape - * The default skewY angle is 0. Positive values distort the node in a CCW direction. - * - * @param fSkewY The Y skew angle of the node in degrees. - */ - virtual void setSkewY(float fSkewY); - /** - * Returns the Y skew angle of the node in degrees. - * - * @see setSkewY(float) - * - * @return The Y skew angle of the node in degrees. - */ - virtual float getSkewY() const; - - - /** - * Sets the anchor point in percent. - * - * anchorPoint is the point around which all transformations and positioning manipulations take place. - * It's like a pin in the node where it is "attached" to its parent. - * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. - * But you can use values higher than (1,1) and lower than (0,0) too. - * The default anchorPoint is (0.5,0.5), so it starts in the center of the node. - * - * @param anchorPoint The anchor point of node. - */ - virtual void setAnchorPoint(const Point& anchorPoint); - /** - * Returns the anchor point in percent. - * - * @see setAnchorPoint(const Point&) - * - * @return The anchor point of node. - */ - virtual const Point& getAnchorPoint() const; - /** - * Returns the anchorPoint in absolute pixels. - * - * @warning You can only read it. If you wish to modify it, use anchorPoint instead. - * @see getAnchorPoint() - * - * @return The anchor point in absolute pixels. - */ - virtual const Point& getAnchorPointInPoints() const; - - - /** - * Sets the untransformed size of the node. - * - * The contentSize remains the same no matter the node is scaled or rotated. - * All nodes has a size. Layer and Scene has the same size of the screen. - * - * @param contentSize The untransformed size of the node. - */ - virtual void setContentSize(const Size& contentSize); - /** - * Returns the untransformed size of the node. - * - * @see setContentSize(const Size&) - * - * @return The untransformed size of the node. - */ - virtual const Size& getContentSize() const; - - - /** - * Sets whether the node is visible - * - * The default value is true, a node is default to visible - * - * @param visible true if the node is visible, false if the node is hidden. - */ - virtual void setVisible(bool visible); - /** - * Determines if the node is visible - * - * @see setVisible(bool) - * - * @return true if the node is visible, false if the node is hidden. - */ - virtual bool isVisible() const; - - - /** - * Sets the rotation (angle) of the node in degrees. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotation The rotation of the node in degrees. - */ - virtual void setRotation(float rotation); - /** - * Returns the rotation of the node in degrees. - * - * @see setRotation(float) - * - * @return The rotation of the node in degrees. - */ - virtual float getRotation() const; - - - /** - * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotationX The X rotation in degrees which performs a horizontal rotational skew. - */ - virtual void setRotationX(float rotationX); - /** - * Gets the X rotation (angle) of the node in degrees which performs a horizontal rotation skew. - * - * @see setRotationX(float) - * - * @return The X rotation in degrees. - */ - virtual float getRotationX() const; - - - /** - * Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. - * - * 0 is the default rotation angle. - * Positive values rotate node clockwise, and negative values for anti-clockwise. - * - * @param rotationY The Y rotation in degrees. - */ - virtual void setRotationY(float rotationY); - /** - * Gets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew. - * - * @see setRotationY(float) - * - * @return The Y rotation in degrees. - */ - virtual float getRotationY() const; - - - /** - * Sets the arrival order when this node has a same ZOrder with other children. - * - * A node which called addChild subsequently will take a larger arrival order, - * If two children have the same Z order, the child with larger arrival order will be drawn later. - * - * @warning This method is used internally for zOrder sorting, don't change this manually - * - * @param orderOfArrival The arrival order. - */ - virtual void setOrderOfArrival(int orderOfArrival); - /** - * Returns the arrival order, indecates which children is added previously. - * - * @see setOrderOfArrival(unsigned int) - * - * @return The arrival order. - */ - virtual int getOrderOfArrival() const; - - - /** @deprecated No longer needed - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE void setGLServerState(int serverState) { /* ignore */ }; - /** @deprecated No longer needed - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE int getGLServerState() const { return 0; } - - /** - * Sets whether the anchor point will be (0,0) when you position this node. - * - * This is an internal method, only used by Layer and Scene. Don't call it outside framework. - * The default value is false, while in Layer and Scene are true - * - * @param ignore true if anchor point will be (0,0) when you position this node - * @todo This method shoud be renamed as setIgnoreAnchorPointForPosition(bool) or something with "set" - */ - virtual void ignoreAnchorPointForPosition(bool ignore); - /** - * Gets whether the anchor point will be (0,0) when you position this node. - * - * @see ignoreAnchorPointForPosition(bool) - * - * @return true if the anchor point will be (0,0) when you position this node. - */ - virtual bool isIgnoreAnchorPointForPosition() const; - - /// @} end of Setters & Getters for Graphic Peroperties - - - /// @{ - /// @name Children and Parent - - /** - * Adds a child to the container with z-order as 0. - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - */ - virtual void addChild(Node * child); - /** - * Adds a child to the container with a z-order - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - */ - virtual void addChild(Node * child, int zOrder); - /** - * Adds a child to the container with z order and tag - * - * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. - * - * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - * @param tag A interger to identify the node easily. Please refer to setTag(int) - */ - virtual void addChild(Node* child, int zOrder, int tag); - /** - * Gets a child from the container with its tag - * - * @param tag An identifier to find the child node. - * - * @return a Node object whose tag equals to the input parameter - */ - Node * getChildByTag(int tag); - /** - * Return an array of children - * - * Composing a "tree" structure is a very important feature of Node - * Here's a sample code of traversing children array: - * @code - * Node* node = NULL; - * CCARRAY_FOREACH(parent->getChildren(), node) - * { - * node->setPosition(0,0); - * } - * @endcode - * This sample code traverses all children nodes, and set their position to (0,0) - * - * @return An array of children - */ - virtual Array* getChildren() { return _children; } - virtual const Array *getChildren() const { return _children; } - - /** - * Get the amount of children. - * - * @return The amount of children. - */ - unsigned int getChildrenCount() const; - - /** - * Sets the parent node - * - * @param parent A pointer to the parnet node - */ - virtual void setParent(Node* parent); - /** - * Returns a pointer to the parent node - * - * @see setParent(Node*) - * - * @returns A pointer to the parnet node - */ - virtual Node* getParent() { return _parent; } - virtual const Node* getParent() const { return _parent; } - - - ////// REMOVES ////// - - /** - * Removes this node itself from its parent node with a cleanup. - * If the node orphan, then nothing happens. - * @see removeFromParentAndCleanup(bool) - */ - virtual void removeFromParent(); - /** - * Removes this node itself from its parent node. - * If the node orphan, then nothing happens. - * @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. - * @js removeFromParent - * @lua removeFromParent - */ - virtual void removeFromParentAndCleanup(bool cleanup); - - /** - * Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. - * - * @param child The child node which will be removed. - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChild(Node* child, bool cleanup = true); - - /** - * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter - * - * @param tag An interger number that identifies a child node - * @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. - */ - virtual void removeChildByTag(int tag, bool cleanup = true); - /** - * Removes all children from the container with a cleanup. - * - * @see removeAllChildrenWithCleanup(bool) - */ - virtual void removeAllChildren(); - /** - * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. - * - * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. - * @js removeAllChildren - * @lua removeAllChildren - */ - virtual void removeAllChildrenWithCleanup(bool cleanup); - - /** - * Reorders a child according to a new z value. - * - * @param child An already added child node. It MUST be already added. - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) - */ - virtual void reorderChild(Node * child, int zOrder); - - /** - * Sorts the children array once before drawing, instead of every time when a child is added or reordered. - * This appraoch can improves the performance massively. - * @note Don't call this manually unless a child added needs to be removed in the same frame - */ - virtual void sortAllChildren(); - - /// @} end of Children and Parent - - - - /// @{ - /// @name Grid object for effects - - /** - * Returns a grid object that is used when applying effects - * - * @return A Grid object that is used when applying effects - * @js NA - */ - virtual GridBase* getGrid() { return _grid; } - /** - * @js NA - */ - virtual const GridBase* getGrid() const { return _grid; } - - /** - * Changes a grid object that is used when applying effects - * - * @param grid A Grid object that is used when applying effects - */ - virtual void setGrid(GridBase *grid); - - /// @} end of Grid - - - /// @{ - /// @name Tag & User data - - /** - * Returns a tag that is used to identify the node easily. - * - * You can set tags to node then identify them easily. - * @code - * #define TAG_PLAYER 1 - * #define TAG_MONSTER 2 - * #define TAG_BOSS 3 - * // set tags - * node1->setTag(TAG_PLAYER); - * node2->setTag(TAG_MONSTER); - * node3->setTag(TAG_BOSS); - * parent->addChild(node1); - * parent->addChild(node2); - * parent->addChild(node3); - * // identify by tags - * Node* node = NULL; - * CCARRAY_FOREACH(parent->getChildren(), node) - * { - * switch(node->getTag()) - * { - * case TAG_PLAYER: - * break; - * case TAG_MONSTER: - * break; - * case TAG_BOSS: - * break; - * } - * } - * @endcode - * - * @return A interger that identifies the node. - */ - virtual int getTag() const; - /** - * Changes the tag that is used to identify the node easily. - * - * Please refer to getTag for the sample code. - * - * @param tag A interger that indentifies the node. - */ - virtual void setTag(int tag); - - /** - * Returns a custom user data pointer - * - * You can set everything in UserData pointer, a data block, a structure or an object. - * - * @return A custom user data pointer - * @js NA - * @lua NA - */ - virtual void* getUserData() { return _userData; } - /** - * @js NA - * @lua NA - */ - virtual const void* getUserData() const { return _userData; } - - /** - * Sets a custom user data pointer - * - * You can set everything in UserData pointer, a data block, a structure or an object, etc. - * @warning Don't forget to release the memroy manually, - * especially before you change this data pointer, and before this node is autoreleased. - * - * @param userData A custom user data pointer - * @js NA - * @lua NA - */ - virtual void setUserData(void *userData); - - /** - * Returns a user assigned Object - * - * Similar to userData, but instead of holding a void* it holds an object - * - * @return A user assigned Object - * @js NA - * @lua NA - */ - virtual Object* getUserObject() { return _userObject; } - /** - * @js NA - * @lua NA - */ - virtual const Object* getUserObject() const { return _userObject; } - - /** - * Returns a user assigned Object - * - * Similar to UserData, but instead of holding a void* it holds an object. - * The UserObject will be retained once in this method, - * and the previous UserObject (if existed) will be relese. - * The UserObject will be released in Node's destructure. - * - * @param userObject A user assigned Object - */ - virtual void setUserObject(Object *userObject); - - /// @} end of Tag & User Data - - - /// @{ - /// @name Shader Program - /** - * Return the shader program currently used for this node - * - * @return The shader program currelty used for this node - */ - virtual GLProgram* getShaderProgram() { return _shaderProgram; } - virtual const GLProgram* getShaderProgram() const { return _shaderProgram; } - - /** - * Sets the shader program for this node - * - * Since v2.0, each rendering node must set its shader program. - * It should be set in initialize phase. - * @code - * node->setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - * @endcode - * - * @param shaderProgram The shader program which fetchs from ShaderCache. - */ - virtual void setShaderProgram(GLProgram *shaderProgram); - /// @} end of Shader Program - - - /** - * Returns a camera object that lets you move the node using a gluLookAt - * - * @code - * Camera* camera = node->getCamera(); - * camera->setEye(0, 0, 415/2); - * camera->setCenter(0, 0, 0); - * @endcode - * - * @return A Camera object that lets you move the node using a gluLookAt - */ - virtual Camera* getCamera(); - - /** - * Returns whether or not the node accepts event callbacks. - * - * Running means the node accept event callbacks like onEnter(), onExit(), update() - * - * @return Whether or not the node is running. - */ - virtual bool isRunning() const; - - /** - * Schedules for lua script. - * @js NA - */ - void scheduleUpdateWithPriorityLua(int handler, int priority); - - /// @} end Script Bindings - - - /// @{ - /// @name Event Callbacks - - /** - * Event callback that is invoked every time when Node enters the 'stage'. - * If the Node enters the 'stage' with a transition, this event is called when the transition starts. - * During onEnter you can't access a "sister/brother" node. - * If you override onEnter, you shall call its parent's one, e.g., Node::onEnter(). - * @js NA - * @lua NA - */ - virtual void onEnter(); - - /** Event callback that is invoked when the Node enters in the 'stage'. - * If the Node enters the 'stage' with a transition, this event is called when the transition finishes. - * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish() - * @js NA - * @lua NA - */ - virtual void onEnterTransitionDidFinish(); - - /** - * Event callback that is invoked every time the Node leaves the 'stage'. - * If the Node leaves the 'stage' with a transition, this event is called when the transition finishes. - * During onExit you can't access a sibling node. - * If you override onExit, you shall call its parent's one, e.g., Node::onExit(). - * @js NA - * @lua NA - */ - virtual void onExit(); - - /** - * Event callback that is called every time the Node leaves the 'stage'. - * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts. - * @js NA - * @lua NA - */ - virtual void onExitTransitionDidStart(); - - /// @} end of event callbacks. - - - /** - * Stops all running actions and schedulers - */ - virtual void cleanup(); - - /** - * Override this method to draw your own node. - * The following GL states will be enabled by default: - * - glEnableClientState(GL_VERTEX_ARRAY); - * - glEnableClientState(GL_COLOR_ARRAY); - * - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - * - glEnable(GL_TEXTURE_2D); - * AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE - * But if you enable any other GL state, you should disable it after drawing your node. - */ - virtual void draw(); - - /** - * Visits this node's children and draw them recursively. - */ - virtual void visit(); - - - /** - * Returns a "local" axis aligned bounding box of the node. - * The returned box is relative only to its parent. - * - * @note This method returns a temporaty variable, so it can't returns const Rect& - * @todo Rename to getBoundingBox() in the future versions. - * - * @return A "local" axis aligned boudning box of the node. - */ - virtual Rect getBoundingBox() const; - - /** @deprecated Use getBoundingBox instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual Rect boundingBox() const { return getBoundingBox(); } - - /// @{ - /// @name Actions - - /** - * Sets the ActionManager object that is used by all actions. - * - * @warning If you set a new ActionManager, then previously created actions will be removed. - * - * @param actionManager A ActionManager object that is used by all actions. - */ - virtual void setActionManager(ActionManager* actionManager); - /** - * Gets the ActionManager object that is used by all actions. - * @see setActionManager(ActionManager*) - * @return A ActionManager object. - */ - virtual ActionManager* getActionManager() { return _actionManager; } - virtual const ActionManager* getActionManager() const { return _actionManager; } - - /** - * Executes an action, and returns the action that is executed. - * - * This node becomes the action's target. Refer to Action::getTarget() - * @warning Actions don't retain their target. - * - * @return An Action pointer - */ - Action* runAction(Action* action); - - /** - * Stops and removes all actions from the running action list . - */ - void stopAllActions(); - - /** - * Stops and removes an action from the running action list. - * - * @param action The action object to be removed. - */ - void stopAction(Action* action); - - /** - * Removes an action from the running action list by its tag. - * - * @param tag A tag that indicates the action to be removed. - */ - void stopActionByTag(int tag); - - /** - * Gets an action from the running action list by its tag. - * - * @see setTag(int), getTag(). - * - * @return The action object with the given tag. - */ - Action* getActionByTag(int tag); - - /** - * Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). - * - * Composable actions are counted as 1 action. Example: - * If you are running 1 Sequence of 7 actions, it will return 1. - * If you are running 7 Sequences of 2 actions, it will return 7. - * @todo Rename to getNumberOfRunningActions() - * - * @return The number of actions that are running plus the ones that are schedule to run - */ - unsigned int getNumberOfRunningActions() const; - - /** @deprecated Use getNumberOfRunningActions() instead */ - CC_DEPRECATED_ATTRIBUTE unsigned int numberOfRunningActions() const { return getNumberOfRunningActions(); }; - - /// @} end of Actions - - - /// @{ - /// @name Scheduler and Timer - - /** - * Sets a Scheduler object that is used to schedule all "updates" and timers. - * - * @warning If you set a new Scheduler, then previously created timers/update are going to be removed. - * @param scheduler A Shdeduler object that is used to schedule all "update" and timers. - */ - virtual void setScheduler(Scheduler* scheduler); - /** - * Gets a Sheduler object. - * - * @see setScheduler(Scheduler*) - * @return A Scheduler object. - */ - virtual Scheduler* getScheduler() { return _scheduler; } - virtual const Scheduler* getScheduler() const { return _scheduler; } - - - /** - * Checks whether a selector is scheduled. - * - * @param selector A function selector - * @return Whether the funcion selector is scheduled. - * @js NA - * @lua NA - */ - bool isScheduled(SEL_SCHEDULE selector); - - /** - * Schedules the "update" method. - * - * It will use the order number 0. This method will be called every frame. - * Scheduled methods with a lower order value will be called before the ones that have a higher order value. - * Only one "update" method could be scheduled per node. - * @js NA - * @lua NA - */ - void scheduleUpdate(void); - - /** - * Schedules the "update" method with a custom priority. - * - * This selector will be called every frame. - * Scheduled methods with a lower priority will be called before the ones that have a higher value. - * Only one "update" selector could be scheduled per node (You can't have 2 'update' selectors). - * @js NA - * @lua NA - */ - void scheduleUpdateWithPriority(int priority); - - /* - * Unschedules the "update" method. - * @see scheduleUpdate(); - */ - void unscheduleUpdate(void); - - /** - * Schedules a custom selector. - * - * If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. - * @code - * // firstly, implement a schedule function - * void MyNode::TickMe(float dt); - * // wrap this function into a selector via schedule_selector marco. - * this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0); - * @endcode - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. - * @param repeat The selector will be excuted (repeat + 1) times, you can use kRepeatForever for tick infinitely. - * @param delay The amount of time that the first tick will wait before execution. - * @lua NA - */ - void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay); - - /** - * Schedules a custom selector with an interval time in seconds. - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param interval Callback interval time in seconds. 0 means tick every frame, - * @lua NA - */ - void schedule(SEL_SCHEDULE selector, float interval); - - /** - * Schedules a selector that runs only once, with a delay of 0 or larger - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector The SEL_SCHEDULE selector to be scheduled. - * @param delay The amount of time that the first tick will wait before execution. - * @lua NA - */ - void scheduleOnce(SEL_SCHEDULE selector, float delay); - - /** - * Schedules a custom selector, the scheduled selector will be ticked every frame - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector A function wrapped as a selector - * @lua NA - */ - void schedule(SEL_SCHEDULE selector); - - /** - * Unschedules a custom selector. - * @see schedule(SEL_SCHEDULE, float, unsigned int, float) - * - * @param selector A function wrapped as a selector - * @lua NA - */ - void unschedule(SEL_SCHEDULE selector); - - /** - * Unschedule all scheduled selectors: custom selectors, and the 'update' selector. - * Actions are not affected by this method. - * @lua NA - */ - void unscheduleAllSelectors(void); - - /** - * Resumes all scheduled selectors and actions. - * This method is called internally by onEnter - */ - void resumeSchedulerAndActions(void); - /** - * Pauses all scheduled selectors and actions. - * This method is called internally by onExit - */ - void pauseSchedulerAndActions(void); - - /* - * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" - */ - virtual void update(float delta); - - /// @} end of Scheduler and Timer - - /// @{ - /// @name Transformations - - /** - * Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. - */ - void transform(); - /** - * Performs OpenGL view-matrix transformation of it's ancestors. - * Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) - * It's necessary to transform the ancestors again. - */ - void transformAncestors(); - /** - * Calls children's updateTransform() method recursively. - * - * This method is moved from Sprite, so it's no longer specific to Sprite. - * As the result, you apply SpriteBatchNode's optimization on your customed Node. - * e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before. - */ - virtual void updateTransform(); - - /** - * Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates. - * The matrix is in Pixels. - */ - virtual const AffineTransform& getNodeToParentTransform() const; - - /** @deprecated use getNodeToParentTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToParentTransform() const { return getNodeToParentTransform(); } - - /** - * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. - * The matrix is in Pixels. - */ - virtual const AffineTransform& getParentToNodeTransform() const; - - /** @deprecated Use getParentToNodeTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform parentToNodeTransform() const { return getParentToNodeTransform(); } - - /** - * Returns the world affine transform matrix. The matrix is in Pixels. - */ - virtual AffineTransform getNodeToWorldTransform() const; - - /** @deprecated Use getNodeToWorldTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToWorldTransform() const { return getNodeToWorldTransform(); } - - /** - * Returns the inverse world affine transform matrix. The matrix is in Pixels. - */ - virtual AffineTransform getWorldToNodeTransform() const; - - /** @deprecated Use worldToNodeTransform() instead */ - CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform worldToNodeTransform() const { return getWorldToNodeTransform(); } - - /// @} end of Transformations - - - /// @{ - /// @name Coordinate Converters - - /** - * Converts a Point to node (local) space coordinates. The result is in Points. - */ - Point convertToNodeSpace(const Point& worldPoint) const; - - /** - * Converts a Point to world space coordinates. The result is in Points. - */ - Point convertToWorldSpace(const Point& nodePoint) const; - - /** - * Converts a Point to node (local) space coordinates. The result is in Points. - * treating the returned/received node point as anchor relative. - */ - Point convertToNodeSpaceAR(const Point& worldPoint) const; - - /** - * Converts a local Point to world space coordinates.The result is in Points. - * treating the returned/received node point as anchor relative. - */ - Point convertToWorldSpaceAR(const Point& nodePoint) const; - - /** - * convenience methods which take a Touch instead of Point - */ - Point convertTouchToNodeSpace(Touch * touch) const; - - /** - * converts a Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative). - */ - Point convertTouchToNodeSpaceAR(Touch * touch) const; - - /** - * Sets the additional transform. - * - * @note The additional transform will be concatenated at the end of getNodeToParentTransform. - * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't). - * @code - // create a batchNode - SpriteBatchNode* batch= SpriteBatchNode::create("Icon-114.png"); - this->addChild(batch); - - // create two sprites, spriteA will be added to batchNode, they are using different textures. - Sprite* spriteA = Sprite::createWithTexture(batch->getTexture()); - Sprite* spriteB = Sprite::create("Icon-72.png"); - - batch->addChild(spriteA); - - // We can't make spriteB as spriteA's child since they use different textures. So just add it to layer. - // But we want to simulate `parent-child` relationship for these two node. - this->addChild(spriteB); - - //position - spriteA->setPosition(Point(200, 200)); - - // Gets the spriteA's transform. - AffineTransform t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - - //scale - spriteA->setScale(2); - - // Gets the spriteA's transform. - t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - - //rotation - spriteA->setRotation(20); - - // Gets the spriteA's transform. - t = spriteA->getNodeToParentTransform(); - - // Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA. - spriteB->setAdditionalTransform(t); - * @endcode - */ - void setAdditionalTransform(const AffineTransform& additionalTransform); - - /// @} end of Coordinate Converters - - /// @{ - /// @name component functions - /** - * gets a component by its name - */ - Component* getComponent(const char *pName); - - /** - * adds a component - */ - virtual bool addComponent(Component *pComponent); - - /** - * removes a component by its name - */ - virtual bool removeComponent(const char *pName); - - /** - * removes all components - */ - virtual void removeAllComponents(); - /// @} end of component functions - - -#ifdef CC_USE_PHYSICS - /** - * set the PhysicsBody that let the sprite effect with physics - */ - void setPhysicsBody(PhysicsBody* body); - - /** - * get the PhysicsBody the sprite have - */ - PhysicsBody* getPhysicsBody() const; - - /** - * update rotation and position from physics body - */ - virtual void updatePhysicsTransform(); -#endif - - -private: - friend class Director; - friend class EventDispatcher; - - int getEventPriority() const { return _eventPriority; }; - - void associateEventListener(EventListener* listener); - void dissociateEventListener(EventListener* listener); - - static void resetEventPriorityIndex(); - std::set _eventlisteners; - -protected: - - /// Upates event priority for this node. - inline void updateEventPriorityIndex() { - _oldEventPriority = _eventPriority; - _eventPriority = ++_globalEventPriorityIndex; - if (_oldEventPriority != _eventPriority) - { - setDirtyForAllEventListeners(); - } - }; - - /// Removes all event listeners that associated with this node. - void removeAllEventListeners(); - - /// Sets dirty for event listener. - void setDirtyForAllEventListeners(); - - /// lazy allocs - void childrenAlloc(void); - - /// helper that reorder a child - void insertChild(Node* child, int z); - - /// Removes a child, call child->onExit(), do cleanup, remove it from children array. - void detachChild(Node *child, int index, bool doCleanup); - - /// Convert cocos2d coordinates to UI windows coordinate. - Point convertToWindowSpace(const Point& nodePoint) const; - - - float _rotationX; ///< rotation angle on x-axis - float _rotationY; ///< rotation angle on y-axis - - float _scaleX; ///< scaling factor on x-axis - float _scaleY; ///< scaling factor on y-axis - - float _vertexZ; ///< OpenGL real Z vertex - - Point _position; ///< position of the node - - float _skewX; ///< skew angle on x-axis - float _skewY; ///< skew angle on y-axis - - Point _anchorPointInPoints; ///< anchor point in points - Point _anchorPoint; ///< anchor point normalized (NOT in points) - - Size _contentSize; ///< untransformed size of the node - - // "cache" variables are allowed to be mutable - mutable AffineTransform _additionalTransform; ///< transform - mutable AffineTransform _transform; ///< transform - mutable AffineTransform _inverse; ///< inverse transform - mutable bool _additionalTransformDirty; ///< The flag to check whether the additional transform is dirty - mutable bool _transformDirty; ///< transform dirty flag - mutable bool _inverseDirty; ///< inverse transform dirty flag - - Camera *_camera; ///< a camera - - GridBase *_grid; ///< a grid - - int _ZOrder; ///< z-order value that affects the draw order - - Array *_children; ///< array of children nodes - Node *_parent; ///< weak reference to parent node - - int _tag; ///< a tag. Can be any number you assigned just to identify this node - - void *_userData; ///< A user assingned void pointer, Can be point to any cpp object - Object *_userObject; ///< A user assigned Object - - GLProgram *_shaderProgram; ///< OpenGL shader - - int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder - - Scheduler *_scheduler; ///< scheduler used to schedule timers and updates - - ActionManager *_actionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions - - bool _running; ///< is running - - bool _visible; ///< is this node visible - - bool _ignoreAnchorPointForPosition; ///< true if the Anchor Point will be (0,0) when you position the Node, false otherwise. - ///< Used by Layer and Scene. - - bool _reorderChildDirty; ///< children order dirty flag - bool _isTransitionFinished; ///< flag to indicate whether the transition was finished - - int _scriptHandler; ///< script handler for onEnter() & onExit(), used in Javascript binding and Lua binding. - int _updateScriptHandler; ///< script handler for update() callback per frame, which is invoked from lua & javascript. - ccScriptType _scriptType; ///< type of script binding, lua or javascript - - ComponentContainer *_componentContainer; ///< Dictionary of components - - int _eventPriority; ///< The scene graph based priority of event listener. - int _oldEventPriority; ///< The old scene graph based priority of event listener. - static int _globalEventPriorityIndex; ///< The index of global event priority. - -#ifdef CC_USE_PHYSICS - PhysicsBody* _physicsBody; ///< the physicsBody the node have -#endif -}; - -//#pragma mark - NodeRGBA - -/** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol. - - All features from Node are valid, plus the following new features: - - opacity - - RGB colors - - Opacity/Color propagates into children that conform to the RGBAProtocol if cascadeOpacity/cascadeColor is enabled. - @since v2.1 - */ -class CC_DLL NodeRGBA : public Node, public RGBAProtocol -{ -public: - /** - * @js ctor - */ - NodeRGBA(); - /** - * @js NA - * @lua NA - */ - virtual ~NodeRGBA(); - - virtual bool init(); - - // overrides - virtual GLubyte getOpacity() const override; - virtual GLubyte getDisplayedOpacity() const override; - virtual void setOpacity(GLubyte opacity) override; - virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; - virtual bool isCascadeOpacityEnabled() const override; - virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override; - - virtual const Color3B& getColor(void) const override; - virtual const Color3B& getDisplayedColor() const override; - virtual void setColor(const Color3B& color) override; - virtual void updateDisplayedColor(const Color3B& parentColor) override; - virtual bool isCascadeColorEnabled() const override; - virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override; - - virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);}; - virtual bool isOpacityModifyRGB() const override { return false; }; - -protected: - GLubyte _displayedOpacity; - GLubyte _realOpacity; - Color3B _displayedColor; - Color3B _realColor; - bool _cascadeColorEnabled; - bool _cascadeOpacityEnabled; -}; - -// end of base_node group -/// @} - -NS_CC_END - -#endif // __PLATFORM_CCNODE_H__ diff --git a/cocos2dx/cocoa/CCGeometry.h b/cocos2dx/cocoa/CCGeometry.h deleted file mode 100644 index 94bbf3fb10..0000000000 --- a/cocos2dx/cocoa/CCGeometry.h +++ /dev/null @@ -1,584 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#ifndef __CCGEMETRY_H__ -#define __CCGEMETRY_H__ - -#include -#include - -#include "platform/CCPlatformMacros.h" -#include "CCObject.h" -#include "ccMacros.h" - -NS_CC_BEGIN - -/** Clamp a value between from and to. - @since v0.99.1 - */ -inline float clampf(float value, float min_inclusive, float max_inclusive) -{ - if (min_inclusive > max_inclusive) { - CC_SWAP(min_inclusive, max_inclusive, float); - } - return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive; -} - -/** - * @addtogroup data_structures - * @{ - */ - -// for Point assignement operator and copy constructor -class CC_DLL Size; - -class CC_DLL Point -{ -public: - float x; - float y; - -public: - /** - * @js NA - */ - Point(); - /** - * @js NA - */ - Point(float x, float y); - /** - * @js NA - * @lua NA - */ - Point(const Point& other); - /** - * @js NA - * @lua NA - */ - explicit Point(const Size& size); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Point& other); - /** - * @js NA - * @lua NA - */ - Point& operator= (const Size& size); - /** - * @js NA - * @lua NA - */ - Point operator+(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point& operator+=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator-(const Point& right) const; - /** - * @js NA - * @lua NA - */ - Point& operator-=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator-() const; - /** - * @js NA - * @lua NA - */ - bool operator==(const Point& right); - /** - * @js NA - * @lua NA - */ - bool operator!=(const Point& right); - /** - * @js NA - * @lua NA - */ - Point operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Point operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setPoint(float x, float y); - /** - * @js NA - */ - bool equals(const Point& target) const; - - /** @returns if points have fuzzy equality which means equal with some degree of variance. - @since v2.1.4 - * @js NA - * @lua NA - */ - bool fuzzyEquals(const Point& target, float variance) const; - - /** Calculates distance between point an origin - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLength() const { - return sqrtf(x*x + y*y); - }; - - /** Calculates the square length of a Point (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getLengthSq() const { - return dot(*this); //x*x + y*y; - }; - - /** Calculates the square distance between two points (not calling sqrt() ) - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistanceSq(const Point& other) const { - return (*this - other).getLengthSq(); - }; - - /** Calculates the distance between two points - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getDistance(const Point& other) const { - return (*this - other).getLength(); - }; - - /** @returns the angle in radians between this vector and the x axis - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float getAngle() const { - return atan2f(y, x); - }; - - /** @returns the angle in radians between two vector directions - @since v2.1.4 - * @js NA - * @lua NA - */ - float getAngle(const Point& other) const; - - /** Calculates dot product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float dot(const Point& other) const { - return x*other.x + y*other.y; - }; - - /** Calculates cross product of two points. - @return float - @since v2.1.4 - * @js NA - * @lua NA - */ - inline float cross(const Point& other) const { - return x*other.y - y*other.x; - }; - - /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getPerp() const { - return Point(-y, x); - }; - - /** Calculates midpoint between two points. - @return Point - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getMidpoint(const Point& other) const - { - return Point((x + other.x) / 2.0f, (y + other.y) / 2.0f); - } - - /** Clamp a point between from and to. - @since v3.0 - * @js NA - * @lua NA - */ - inline Point getClampPoint(const Point& min_inclusive, const Point& max_inclusive) const - { - return Point(clampf(x,min_inclusive.x,max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y)); - } - - /** Run a math operation function on each point component - * absf, fllorf, ceilf, roundf - * any function that has the signature: float func(float); - * For example: let's try to take the floor of x,y - * p.compOp(floorf); - @since v3.0 - * @js NA - * @lua NA - */ - inline Point compOp(std::function function) const - { - return Point(function(x), function(y)); - } - - /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point getRPerp() const { - return Point(y, -x); - }; - - /** Calculates the projection of this over other. - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point project(const Point& other) const { - return other * (dot(other)/other.dot(other)); - }; - - /** Complex multiplication of two points ("rotates" two points). - @return Point vector with an angle of this.getAngle() + other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point rotate(const Point& other) const { - return Point(x*other.x - y*other.y, x*other.y + y*other.x); - }; - - /** Unrotates two points. - @return Point vector with an angle of this.getAngle() - other.getAngle(), - and a length of this.getLength() * other.getLength(). - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point unrotate(const Point& other) const { - return Point(x*other.x + y*other.y, y*other.x - x*other.y); - }; - - /** Returns point multiplied to a length of 1. - * If the point is 0, it returns (1, 0) - @return Point - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point normalize() const { - float length = getLength(); - if(length == 0.) return Point(1.f, 0); - return *this / getLength(); - }; - - /** Linear Interpolation between two points a and b - @returns - alpha == 0 ? a - alpha == 1 ? b - otherwise a value between a..b - @since v2.1.4 - * @js NA - * @lua NA - */ - inline Point lerp(const Point& other, float alpha) const { - return *this * (1.f - alpha) + other * alpha; - }; - - /** Rotates a point counter clockwise by the angle around a pivot - @param pivot is the pivot, naturally - @param angle is the angle of rotation ccw in radians - @returns the rotated point - @since v2.1.4 - * @js NA - * @lua NA - */ - Point rotateByAngle(const Point& pivot, float angle) const; - - /** - * @js NA - * @lua NA - */ - static inline Point forAngle(const float a) - { - return Point(cosf(a), sinf(a)); - } - - /** A general line-line intersection test - @param A the startpoint for the first line L1 = (A - B) - @param B the endpoint for the first line L1 = (A - B) - @param C the startpoint for the second line L2 = (C - D) - @param D the endpoint for the second line L2 = (C - D) - @param S the range for a hitpoint in L1 (p = A + S*(B - A)) - @param T the range for a hitpoint in L2 (p = C + T*(D - C)) - @returns whether these two lines interects. - - Note that to truly test intersection for segments we have to make - sure that S & T lie within [0..1] and for rays, make sure S & T > 0 - the hit point is C + T * (D - C); - the hit point also is A + S * (B - A); - @since 3.0 - * @js NA - * @lua NA - */ - static bool isLineIntersect(const Point& A, const Point& B, - const Point& C, const Point& D, - float *S = nullptr, float *T = nullptr); - - /** - returns true if Line A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineOverlap(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Line A-B parallel with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isLineParallel(const Point& A, const Point& B, - const Point& C, const Point& D); - - /** - returns true if Segment A-B overlap with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentOverlap(const Point& A, const Point& B, - const Point& C, const Point& D, - Point* S = nullptr, Point* E = nullptr); - - /** - returns true if Segment A-B intersects with segment C-D - @since v3.0 - * @js NA - * @lua NA - */ - static bool isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D); - - /** - returns the intersection point of line A-B, C-D - @since v3.0 - * @js NA - * @lua NA - */ - static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); - - static const Point ZERO; - -private: - // returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part - static bool isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E); - - // cross procuct of 2 vector. A->B X C->D - static float crossProduct2Vector(const Point& A, const Point& B, const Point& C, const Point& D) { return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y); } -}; - -class CC_DLL Size -{ -public: - float width; - float height; - -public: - /** - * @js NA - */ - Size(); - /** - * @js NA - */ - Size(float width, float height); - /** - * @js NA - * @lua NA - */ - Size(const Size& other); - /** - * @js NA - * @lua NA - */ - explicit Size(const Point& point); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Size& other); - /** - * @js NA - * @lua NA - */ - Size& operator= (const Point& point); - /** - * @js NA - * @lua NA - */ - Size operator+(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator-(const Size& right) const; - /** - * @js NA - * @lua NA - */ - Size operator*(float a) const; - /** - * @js NA - * @lua NA - */ - Size operator/(float a) const; - /** - * @js NA - * @lua NA - */ - void setSize(float width, float height); - /** - * @js NA - */ - bool equals(const Size& target) const; - - static const Size ZERO; -}; - -class CC_DLL Rect -{ -public: - Point origin; - Size size; - -public: - /** - * @js NA - */ - Rect(); - /** - * @js NA - */ - Rect(float x, float y, float width, float height); - /** - * @js NA - * @lua NA - */ - Rect(const Rect& other); - /** - * @js NA - * @lua NA - */ - Rect& operator= (const Rect& other); - /** - * @js NA - * @lua NA - */ - void setRect(float x, float y, float width, float height); - /** - * @js NA - */ - float getMinX() const; /// return the leftmost x-value of current rect - /** - * @js NA - */ - float getMidX() const; /// return the midpoint x-value of current rect - /** - * @js NA - */ - float getMaxX() const; /// return the rightmost x-value of current rect - /** - * @js NA - */ - float getMinY() const; /// return the bottommost y-value of current rect - /** - * @js NA - */ - float getMidY() const; /// return the midpoint y-value of current rect - /** - * @js NA - */ - float getMaxY() const; /// return the topmost y-value of current rect - /** - * @js NA - */ - bool equals(const Rect& rect) const; - /** - * @js NA - */ - bool containsPoint(const Point& point) const; - /** - * @js NA - */ - bool intersectsRect(const Rect& rect) const; - /** - * @js NA - * @lua NA - */ - Rect unionWithRect(const Rect & rect) const; - - static const Rect ZERO; -}; - -// end of data_structure group -/// @} - -NS_CC_END - -#endif // __CCGEMETRY_H__ diff --git a/cocos2dx/physics/CCPhysicsBody.h b/cocos2dx/physics/CCPhysicsBody.h deleted file mode 100644 index 869c7be1da..0000000000 --- a/cocos2dx/physics/CCPhysicsBody.h +++ /dev/null @@ -1,292 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_BODY_H__ -#define __CCPHYSICS_BODY_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -#include "CCPhysicsShape.h" - -#include - -NS_CC_BEGIN -class Sprite; -class PhysicsWorld; -class PhysicsJoint; - -class PhysicsBodyInfo; - - -const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; - -/** - * A body affect by physics. - * it can attach one or more shapes. - */ -class PhysicsBody : public Object//, public Clonable -{ -public: - static PhysicsBody* create(); - /** - * @brief Create a body contains a circle shape. - */ - static PhysicsBody* createCircle(float radius, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - /** - * @brief Create a body contains a box shape. - */ - static PhysicsBody* createBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - /** - * @brief Create a body contains a polygon shape. - * points is an array of Point structs defining a convex hull with a clockwise winding. - */ - static PhysicsBody* createPolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT); - - /** - * @brief Create a body contains a EdgeSegment shape. - */ - static PhysicsBody* createEdgeSegment(Point a, Point b, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgeBox shape. - */ - static PhysicsBody* createEdgeBox(Size size, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgePolygon shape. - */ - static PhysicsBody* createEdgePolygon(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - /** - * @brief Create a body contains a EdgeChain shape. - */ - static PhysicsBody* createEdgeChain(Point* points, int count, PhysicsMaterial material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1); - - virtual void addShape(PhysicsShape* shape); - - /** - * @brief Applies a immediate force to body. - */ - virtual void applyForce(Point force); - /** - * @brief Applies a immediate force to body. - */ - virtual void applyForce(Point force, Point offset); - /** - * @brief Applies a continuous force to body. - */ - virtual void applyImpulse(Point impulse); - /** - * @brief Applies a continuous force to body. - */ - virtual void applyImpulse(Point impulse, Point offset); - /** - * @brief Applies a torque force to body. - */ - virtual void applyTorque(float torque); - - virtual void setVelocity(Point velocity); - virtual Point getVelocity(); - virtual void setAngularVelocity(float velocity); - virtual float getAngularVelocity(); - virtual void setVelocityLimit(float limit); - virtual float getVelocityLimit(); - virtual void setAngularVelocityLimit(float limit); - virtual float getAngularVelocityLimit(); - - /* - * @brief get the body shapes. - */ - inline std::vector& getShapes() { return _shapes; } - /* - * @brief get the first body shapes. - */ - inline PhysicsShape* getShape() { return _shapes.size() >= 1 ? _shapes.front() : nullptr; } - PhysicsShape* getShapeByTag(int tag); - /* - * @brief remove a shape from body - */ - void removeShape(PhysicsShape* shape); - void removeShapeByTag(int tag); - /* - * @brief remove all shapes - */ - void removeAllShapes(); - - /* - * @brief get the world body added to. - */ - inline PhysicsWorld* getWorld() const { return _world; } - /* - * @brief get all joints the body have - */ - inline const std::vector* getJoints() const { return &_joints; } - - /* - * @brief get the sprite the body set to. - */ - inline Sprite* getOwner() const { return _owner; } - - inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; } - inline int getCategoryBitmask() const { return _categoryBitmask; } - inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; } - inline int getContactTestBitmask() const { return _contactTestBitmask; } - inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; } - inline int getCollisionBitmask() const { return _collisionBitmask; } - - /* - * @brief get the body position. - */ - Point getPosition() const; - /* - * @brief get the body rotation. - */ - float getRotation() const; - - /* - * @brief test the body is dynamic or not. - * a dynamic body will effect with gravity. - */ - inline bool isDynamic() { return _dynamic; } - /* - * @brief set dynamic to body. - * a dynamic body will effect with gravity. - */ - void setDynamic(bool dynamic); - - /* - * @brief set the body mass. - * @note if you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead. - */ - void setMass(float mass); - /* - * @brief get the body mass. - */ - inline float getMass() { return _mass; } - /* - * @brief add mass to body. - * if _mass(mass of the body) == PHYSICS_INFINITY, it remains. - * if mass == PHYSICS_INFINITY, _mass will be PHYSICS_INFINITY. - * if mass == -PHYSICS_INFINITY, _mass will not change. - * if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0) - * other wise, mass = mass + _mass; - */ - void addMass(float mass); - - /* - * @brief set the body moment of inertia. - * @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead. - */ - void setMoment(float moment); - /* - * @brief get the body moment of inertia. - */ - inline float getMoment(float moment) { return _moment; } - /* - * @brief add moment of inertia to body. - * if _moment(moment of the body) == PHYSICS_INFINITY, it remains. - * if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY. - * if moment == -PHYSICS_INFINITY, _moment will not change. - * if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0) - * other wise, moment = moment + _moment; - */ - void addMoment(float moment); - /* - * @brief set angular damping. - */ - //void setAngularDamping(float angularDamping); - /* - * @brief get angular damping. - */ - inline float getLinearDamping() { return _linearDamping; } - inline void setLinearDamping(float damping) { _linearDamping = damping; } - inline float getAngularDamping() { return _angularDamping; } - inline void setAngularDamping(float damping) { _angularDamping = damping; } - - //virtual Clonable* clone() const override; - - bool isResting(); - inline bool isEnable() { return _enable; } - void setEnable(bool enable); - - inline bool isRotationEnable() { return _rotationEnable; } - void setRotationEnable(bool enable); - - inline bool isGravityEnable() { return _gravityEnable; } - void setGravityEnable(bool enable); - - - inline int getTag() { return _tag; } - inline void setTag(int tag) { _tag = tag; } - - -protected: - - bool init(); - - virtual void setPosition(Point position); - virtual void setRotation(float rotation); - - virtual void update(float delta) override; - -protected: - PhysicsBody(); - virtual ~PhysicsBody(); - -protected: - Sprite* _owner; - std::vector _joints; - std::vector _shapes; - PhysicsWorld* _world; - PhysicsBodyInfo* _info; - bool _dynamic; - bool _enable; - bool _rotationEnable; - bool _gravityEnable; - bool _massDefault; - bool _momentDefault; - float _mass; - float _area; - float _density; - float _moment; - float _linearDamping; - float _angularDamping; - int _tag; - - int _categoryBitmask; - int _contactTestBitmask; - int _collisionBitmask; - - friend class PhysicsWorld; - friend class PhysicsShape; - friend class PhysicsJoint; - friend class Node; -}; - -NS_CC_END - -#endif // __CCPHYSICS_BODY_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsContact.h b/cocos2dx/physics/CCPhysicsContact.h deleted file mode 100644 index df31ae7be3..0000000000 --- a/cocos2dx/physics/CCPhysicsContact.h +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_CONTACT_H__ -#define __CCPHYSICS_CONTACT_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsShape; -class PhysicsWorld; - -class PhysicsContactInfo; - -/** - * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. - */ -class PhysicsContact -{ -public: - /* - * @brief get contact shape A. - */ - inline PhysicsShape* getShapeA() const { return _shapeA; } - /* - * @brief get contact shape B. - */ - inline PhysicsShape* getShapeB() const { return _shapeB; } - /* - * @brief get data. - */ - inline void* getData() { return _data; } - /* - * @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact end. - */ - inline void setData(void* data) { _data = data; } - -private: - static PhysicsContact* create(PhysicsShape* a, PhysicsShape* b); - bool init(PhysicsShape* a, PhysicsShape* b); - - inline bool getNotify() { return _notify; } - inline void setNotify(bool notify) { _notify = notify; } - -private: - PhysicsContact(); - ~PhysicsContact(); - -private: - PhysicsShape* _shapeA; - PhysicsShape* _shapeB; - PhysicsContactInfo* _info; - void* _data; - bool _notify; - - friend class PhysicsWorld; -}; - -/* - * @brief presolve value generated when onContactPreSolve called. - */ -class PhysicsContactPreSolve -{ -private: - PhysicsContactPreSolve(); - ~PhysicsContactPreSolve(); - - static PhysicsContactPreSolve* create(); - bool init(); - - friend class PhysicsWorld; -}; - -/* - * @brief postsolve value generated when onContactPostSolve called. - */ -class PhysicsContactPostSolve -{ -private: - PhysicsContactPostSolve(); - ~PhysicsContactPostSolve(); - - static PhysicsContactPostSolve* create(); - bool init(); - - friend class PhysicsWorld; -}; - -/* - * @brief contact listener. - */ -class PhysicsContactListener -{ -public: - PhysicsContactListener(); - virtual ~PhysicsContactListener(); - -public: - /* - * @brief it will called at two shapes start to contact, and only call it once. - */ - std::function onContactBegin; - /* - * @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, elasticity, or surface velocity values. - */ - std::function onContactPreSolve; - /* - * @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info - */ - std::function onContactPostSolve; - /* - * @brief it will called at two shapes separated, and only call it once. - * onContactBegin and onContactEnd will called in pairs. - */ - std::function onContactEnd; -}; - -NS_CC_END -#endif //__CCPHYSICS_CONTACT_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsJoint.h b/cocos2dx/physics/CCPhysicsJoint.h deleted file mode 100644 index ebc7ceddc0..0000000000 --- a/cocos2dx/physics/CCPhysicsJoint.h +++ /dev/null @@ -1,168 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_JOINT_H__ -#define __CCPHYSICS_JOINT_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsBody; -class PhysicsJointInfo; -class PhysicsBodyInfo; - -/* - * @brief An PhysicsJoint object connects two physics bodies together. - */ -class PhysicsJoint : public Object -{ -protected: - PhysicsJoint(); - virtual ~PhysicsJoint() = 0; - -public: - PhysicsBody* getBodyA() { return _bodyA; } - PhysicsBody* getBodyB() { return _bodyB; } - inline int getTag() { return _tag; } - inline void setTag(int tag) { _tag = tag; } - inline bool isEnable() { return _enable; } - void setEnable(bool enable); - inline bool isCollisionEnable() { return _collisionEnable; } - void setCollisionEnable(bool enable); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b); - - /** - * PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. - */ - PhysicsBodyInfo* bodyInfo(PhysicsBody* body) const; - -protected: - PhysicsBody* _bodyA; - PhysicsBody* _bodyB; - PhysicsJointInfo* _info; - bool _enable; - bool _collisionEnable; - int _tag; - - friend class PhysicsBody; - friend class PhysicsWorld; -}; - -/* - * @brief A fixed joint fuses the two bodies together at a reference point. Fixed joints are useful for creating complex shapes that can be broken apart later. - */ -class PhysicsJointFixed : public PhysicsJoint -{ -public: - PhysicsJointFixed* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - PhysicsJointFixed(); - virtual ~PhysicsJointFixed(); -}; - -/* - * @brief A sliding joint allows the two bodies to slide along a chosen axis. - */ -class PhysicsJointSliding : public PhysicsJoint -{ -public: - PhysicsJointSliding* create(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& grooveA, const Point& grooveB, const Point& anchr); - -protected: - PhysicsJointSliding(); - virtual ~PhysicsJointSliding(); -}; - -/* - * @brief A spring joint connects the two bodies with a spring whose length is the initial distance between the two bodies. - */ -class PhysicsJointSpring : public PhysicsJoint -{ -public: - PhysicsJointSpring* create(); - -protected: - bool init(); - -protected: - PhysicsJointSpring(); - virtual ~PhysicsJointSpring(); -}; - -/* - * @brief A limit joint imposes a maximum distance between the two bodies, as if they were connected by a rope. - */ -class PhysicsJointLimit : public PhysicsJoint -{ -public: - PhysicsJointLimit* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - - float getMin(); - void setMin(float min); - float getMax(); - void setMax(float max); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr1, const Point& anchr2); - -protected: - PhysicsJointLimit(); - virtual ~PhysicsJointLimit(); -}; - -/* - * @brief A pin joint allows the two bodies to independently rotate around the anchor point as if pinned together. - */ -class PhysicsJointPin : public PhysicsJoint -{ -public: - static PhysicsJointPin* create(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - bool init(PhysicsBody* a, PhysicsBody* b, const Point& anchr); - -protected: - PhysicsJointPin(); - virtual ~PhysicsJointPin(); -}; - -NS_CC_END - -#endif // __CCPHYSICS_JOINT_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsShape.h b/cocos2dx/physics/CCPhysicsShape.h deleted file mode 100644 index fcf70c7c19..0000000000 --- a/cocos2dx/physics/CCPhysicsShape.h +++ /dev/null @@ -1,296 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_SHAPE_H__ -#define __CCPHYSICS_SHAPE_H__ - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsShapeInfo; -class PhysicsBody; -class PhysicsBodyInfo; - - -typedef struct PhysicsMaterial -{ - float density; - float restitution; - float friction; - - PhysicsMaterial() - : density(0.0f) - , restitution(0.0f) - , friction(0.0f){} - - PhysicsMaterial(float density, float restitution, float friction) - : density(density) - , restitution(restitution) - , friction(friction){} -}PhysicsMaterial; - -const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0f, 1.0f, 1.0f}; - -/** - * @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it. - */ -class PhysicsShape : public Object -{ -public: - enum class Type - { - UNKNOWN, - CIRCLE, - BOX, - POLYGEN, - EDGESEGMENT, - EDGEBOX, - EDGEPOLYGEN, - EDGECHAIN, - }; - -public: - inline PhysicsBody* getBody() const { return _body; } - inline Type getType() const { return _type; } - inline float getArea() const { return _area; } - inline float getMoment() const { return _moment; } - void setMoment(float moment); - inline void setTag(int tag) { _tag = tag; } - inline int getTag() const { return _tag; } - - inline float getMass() const { return _mass; } - void setMass(float mass); - inline float getDensity() const { return _material.density; } - void setDensity(float density); - void setRestitution(float restitution); - void setFriction(float friction); - void setMaterial(PhysicsMaterial material); - - virtual float calculateDefaultMoment() { return 0; } - virtual float calculateDefaultArea() { return 0; } - virtual Point getOffset() { return Point::ZERO; } - virtual Point getCenter() { return getOffset(); } - - static Point* recenterPoints(Point* points, int count, Point center); - static Point getPolyonCenter(Point* points, int count); - -protected: - bool init(Type type); - - /** - * @brief PhysicsShape is PhysicsBody's friend class, but all the subclasses isn't. so this method is use for subclasses to catch the bodyInfo from PhysicsBody. - */ - PhysicsBodyInfo* bodyInfo() const; - - void setBody(PhysicsBody* body); - -protected: - PhysicsShape(); - virtual ~PhysicsShape() = 0; - -protected: - PhysicsBody* _body; - PhysicsShapeInfo* _info; - Type _type; - float _area; - float _mass; - float _moment; - PhysicsMaterial _material; - int _tag; - - friend class PhysicsWorld; - friend class PhysicsBody; - friend class PhysicsJoint; -}; - -/** A circle shape */ -class PhysicsShapeCircle : public PhysicsShape -{ -public: - static PhysicsShapeCircle* create(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(float radius); - static float calculateMoment(float mass, float radius, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - float getRadius(); - Point getOffset(); -protected: - bool init(float radius, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapeCircle(); - ~PhysicsShapeCircle(); -}; - -/** A box shape */ -class PhysicsShapeBox : public PhysicsShape -{ -public: - static PhysicsShapeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Size size); - static float calculateMoment(float mass, Size size, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - Point* getPoints(Point* points); - Size getSize(); - Point getOffset() override { return _offset; } - -protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapeBox(); - virtual ~PhysicsShapeBox(); - -protected: - Point _offset; -}; - -/** A polygon shape */ -class PhysicsShapePolygon : public PhysicsShape -{ -public: - static PhysicsShapePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - static float calculateArea(Point* points, int count); - static float calculateMoment(float mass, Point* points, int count, Point offset = Point(0, 0)); - - float calculateDefaultArea() override; - float calculateDefaultMoment() override; - - Point* getPoints(Point* points); - int getPointsCount(); - Point getCenter() override; -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, Point offset = Point(0, 0)); - -protected: - PhysicsShapePolygon(); - virtual ~PhysicsShapePolygon(); - -protected: - Point _center; -}; - -/** A segment shape */ -class PhysicsShapeEdgeSegment : public PhysicsShape -{ -public: - static PhysicsShapeEdgeSegment* create(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - - Point getPointA(); - Point getPointB(); - Point getCenter() override; - -protected: - bool init(Point a, Point b, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgeSegment(); - virtual ~PhysicsShapeEdgeSegment(); - -protected: - Point _center; - - friend class PhysicsBody; -}; - -/** An edge box shape */ -class PhysicsShapeEdgeBox : public PhysicsShape -{ -public: - static PhysicsShapeEdgeBox* create(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, Point offset = Point(0, 0)); - Point getOffset() override { return _offset; } - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Size size, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1, Point offset = Point(0, 0)); - -protected: - PhysicsShapeEdgeBox(); - virtual ~PhysicsShapeEdgeBox(); - -protected: - Point _offset; - - friend class PhysicsBody; -}; - -/** An edge polygon shape */ -class PhysicsShapeEdgePolygon : public PhysicsShape -{ -public: - static PhysicsShapeEdgePolygon* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgePolygon(); - virtual ~PhysicsShapeEdgePolygon(); - - friend class PhysicsBody; - -protected: - Point _center; -}; - -/** a chain shape */ -class PhysicsShapeEdgeChain : public PhysicsShape -{ -public: - static PhysicsShapeEdgeChain* create(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - Point getCenter() override; - Point* getPoints(Point* points); - int getPointsCount(); - -protected: - bool init(Point* points, int count, PhysicsMaterial material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1); - -protected: - PhysicsShapeEdgeChain(); - virtual ~PhysicsShapeEdgeChain(); - -protected: - Point _center; - - friend class PhysicsBody; -}; - -NS_CC_END -#endif // __CCPHYSICS_FIXTURE_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsWorld.cpp b/cocos2dx/physics/CCPhysicsWorld.cpp deleted file mode 100644 index afccdca8d9..0000000000 --- a/cocos2dx/physics/CCPhysicsWorld.cpp +++ /dev/null @@ -1,496 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsWorld.h" -#ifdef CC_USE_PHYSICS - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -#include "chipmunk.h" -#elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) -#include "Box2D.h" -#endif - -#include "CCPhysicsBody.h" -#include "CCPhysicsShape.h" -#include "CCPhysicsContact.h" -#include "CCPhysicsJoint.h" -#include "CCPhysicsContact.h" - -#include "chipmunk/CCPhysicsWorldInfo.h" -#include "Box2D/CCPhysicsWorldInfo.h" -#include "chipmunk/CCPhysicsBodyInfo.h" -#include "Box2D/CCPhysicsBodyInfo.h" -#include "chipmunk/CCPhysicsShapeInfo.h" -#include "Box2D/CCPhysicsShapeInfo.h" -#include "chipmunk/CCPhysicsContactInfo.h" -#include "Box2D/CCPhysicsContactInfo.h" -#include "chipmunk/CCPhysicsJointInfo.h" -#include "Box2D/CCPhysicsJointInfo.h" -#include "chipmunk/CCPhysicsHelper.h" - -#include "draw_nodes/CCDrawNode.h" -#include "cocoa/CCArray.h" -#include "layers_scenes_transitions_nodes/CCScene.h" -#include "CCDirector.h" - -#include - -NS_CC_BEGIN - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -const float PHYSICS_INFINITY = INFINITY; - -int PhysicsWorld::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - - CP_ARBITER_GET_SHAPES(arb, a, b); - - auto ita = PhysicsShapeInfo::map.find(a); - auto itb = PhysicsShapeInfo::map.find(b); - CC_ASSERT(ita != PhysicsShapeInfo::map.end() && itb != PhysicsShapeInfo::map.end()); - - PhysicsContact* contact = PhysicsContact::create(ita->second->shape, itb->second->shape); - arb->data = contact; - - return world->collisionBeginCallback(*static_cast(arb->data)); -} - -int PhysicsWorld::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - return world->collisionPreSolveCallback(*static_cast(arb->data), - PhysicsContactPreSolve()); -} - -void PhysicsWorld::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - world->collisionPostSolveCallback(*static_cast(arb->data), - PhysicsContactPostSolve()); -} - -void PhysicsWorld::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data) -{ - PhysicsWorld* world = static_cast(data); - PhysicsContact* contact = static_cast(arb->data); - - world->collisionSeparateCallback(*contact); - - delete contact; -} - -bool PhysicsWorld::init() -{ - _info = new PhysicsWorldInfo(); - - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(_gravity)); - - cpSpaceSetDefaultCollisionHandler(_info->space, - PhysicsWorld::collisionBeginCallbackFunc, - PhysicsWorld::collisionPreSolveCallbackFunc, - PhysicsWorld::collisionPostSolveCallbackFunc, - PhysicsWorld::collisionSeparateCallbackFunc, - this); - - return true; -} - -void PhysicsWorld::addJoint(PhysicsJoint* joint) -{ - auto it = std::find(_joints.begin(), _joints.end(), joint); - - if (it == _joints.end()) - { - _joints.push_back(joint); - - for (auto subjoint : joint->_info->joints) - { - if (!cpSpaceContainsConstraint(_info->space, subjoint)) - { - cpSpaceAddConstraint(_info->space, subjoint); - } - } - } - -} - -void PhysicsWorld::removeJoint(PhysicsJoint* joint) -{ - -} - -void PhysicsWorld::removeAllJoints() -{ - -} - -void PhysicsWorld::addShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - continue; - } - - if (cpBodyIsStatic(shape->getBody()->_info->body)) - { - cpSpaceAddStaticShape(_info->space, cps); - }else - { - cpSpaceAddShape(_info->space, cps); - } - } -} - -void PhysicsWorld::addBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - if (body->isEnable()) - { - //is gravity enable - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - - // add body to space - if (body->isDynamic()) - { - cpSpaceAddBody(_info->space, body->_info->body); - } - - // add shapes to space - for (auto shape : body->getShapes()) - { - addShape(shape); - } - } - - if (_bodys == nullptr) - { - _bodys = Array::create(body, NULL); - _bodys->retain(); - }else - { - _bodys->addObject(body); - } -} - -void PhysicsWorld::removeBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - if (body->getWorld() == this) - { - // reset the gravity - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - } - } - - // remove shaps - for (auto shape : body->getShapes()) - { - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } - } - - // remove body - if (cpSpaceContainsBody(_info->space, body->_info->body)) - { - cpSpaceRemoveBody(_info->space, body->_info->body); - } - - if (_bodys != nullptr) - { - _bodys->removeObject(body); - } -} - -void PhysicsWorld::removeBodyByTag(int tag) -{ - for (Object* obj : *_bodys) - { - PhysicsBody* body = dynamic_cast(obj); - if (body->getTag() == tag) - { - removeBody(body); - return; - } - } -} - -void PhysicsWorld::removeShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->shapes) - { - if (cpSpaceContainsShape(_info->space, cps)) - { - cpSpaceRemoveShape(_info->space, cps); - } - } -} - -void PhysicsWorld::update(float delta) -{ - for (auto body : *_bodys) - { - body->update(delta); - } - - cpSpaceStep(_info->space, delta); - - if (_drawNode) - { - _drawNode->removeFromParent(); - _drawNode = nullptr; - } - - if (_debugDraw) - { - debugDraw(); - } -} - -void PhysicsWorld::debugDraw() -{ - if (_debugDraw && _bodys != nullptr) - { - _drawNode= DrawNode::create(); - - for (Object* obj : *_bodys) - { - PhysicsBody* body = dynamic_cast(obj); - - std::vector shapes = body->getShapes(); - - for (auto shape : shapes) - { - drawWithShape(_drawNode, shape); - } - } - - if (_scene) - { - _scene->addChild(_drawNode); - } - } -} - -void PhysicsWorld::setScene(Scene *scene) -{ - _scene = scene; -} - -void PhysicsWorld::drawWithShape(DrawNode* node, PhysicsShape* shape) -{ - for (auto it = shape->_info->shapes.begin(); it != shape->_info->shapes.end(); ++it) - { - cpShape *shape = *it; - - switch ((*it)->klass_private->type) - { - case CP_CIRCLE_SHAPE: - { - float radius = PhysicsHelper::cpfloat2float(cpCircleShapeGetRadius(shape)); - Point centre = PhysicsHelper::cpv2point(cpBodyGetPos(cpShapeGetBody(shape))) - + PhysicsHelper::cpv2point(cpCircleShapeGetOffset(shape)); - - Point seg[4] = {}; - seg[0] = Point(centre.x - radius, centre.y - radius); - seg[1] = Point(centre.x - radius, centre.y + radius); - seg[2] = Point(centre.x + radius, centre.y + radius); - seg[3] = Point(centre.x + radius, centre.y - radius); - node->drawPolygon(seg, 4, Color4F(), 1, Color4F(1, 0, 0, 1)); - break; - } - case CP_SEGMENT_SHAPE: - { - cpSegmentShape *seg = (cpSegmentShape *)shape; - node->drawSegment(PhysicsHelper::cpv2point(seg->ta), - PhysicsHelper::cpv2point(seg->tb), - PhysicsHelper::cpfloat2float(seg->r==0 ? 1 : seg->r), Color4F(1, 0, 0, 1)); - break; - } - case CP_POLY_SHAPE: - { - cpPolyShape* poly = (cpPolyShape*)shape; - int num = poly->numVerts; - Point* seg = new Point[num]; - - PhysicsHelper::cpvs2points(poly->tVerts, seg, num); - - node->drawPolygon(seg, num, Color4F(1.0f, 0.0f, 0.0f, 0.3f), 1.0f, Color4F(1.0f, 0.0f, 0.0f, 1.0f)); - - delete[] seg; - break; - } - default: - break; - } - } -} - -int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) -{ - bool ret = true; - PhysicsBody* bodyA = contact.getShapeA()->getBody(); - PhysicsBody* bodyB = contact.getShapeB()->getBody(); - - if ((bodyA->getCategoryBitmask() & bodyB->getContactTestBitmask()) == 0) - { - contact.setNotify(false); - } - - if ((bodyA->getCategoryBitmask() & bodyB->getCollisionBitmask()) == 0) - { - ret = false; - } - - if (contact.getNotify() && _listener && _listener->onContactBegin) - { - // the mask has high priority than _listener->onContactBegin. - // so if the mask test is false, the two bodies won't have collision. - if (ret) - { - ret = _listener->onContactBegin(contact); - }else - { - _listener->onContactBegin(contact); - } - } - - return ret; -} - -int PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve) -{ - if (!contact.getNotify()) - { - return true; - } - - if (_listener && _listener->onContactPreSolve) - { - return _listener->onContactPreSolve(contact, solve); - } - - return true; -} - -void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve) -{ - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactPreSolve) - { - _listener->onContactPostSolve(contact, solve); - } -} - -void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) -{ - if (!contact.getNotify()) - { - return; - } - - if (_listener && _listener->onContactEnd) - { - _listener->onContactEnd(contact); - } -} - -void PhysicsWorld::setGravity(Point gravity) -{ - if (_bodys != nullptr) - { - for (auto child : *_bodys) - { - PhysicsBody* body = dynamic_cast(child); - - // reset gravity for body - if (!body->isGravityEnable()) - { - body->applyForce(-_gravity); - body->applyForce(gravity); - } - } - } - - _gravity = gravity; - cpSpaceSetGravity(_info->space, PhysicsHelper::point2cpv(gravity)); -} - -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#endif - -PhysicsWorld* PhysicsWorld::create() -{ - PhysicsWorld * world = new PhysicsWorld(); - if(world && world->init()) - { - return world; - } - - CC_SAFE_DELETE(world); - return nullptr; -} - -PhysicsWorld::PhysicsWorld() -: _gravity(Point(0.0f, -98.0f)) -, _speed(1.0f) -, _info(nullptr) -, _listener(nullptr) -, _bodys(nullptr) -, _scene(nullptr) -, _debugDraw(false) -, _drawNode(nullptr) -{ - -} - -PhysicsWorld::~PhysicsWorld() -{ - CC_SAFE_DELETE(_info); - CC_SAFE_RELEASE(_bodys); -} - -NS_CC_END - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/CCPhysicsWorld.h b/cocos2dx/physics/CCPhysicsWorld.h deleted file mode 100644 index a0539ae81d..0000000000 --- a/cocos2dx/physics/CCPhysicsWorld.h +++ /dev/null @@ -1,149 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCPhysicsSetting.h" -#ifdef CC_USE_PHYSICS - -#ifndef __CCPHYSICS_WORLD_H__ -#define __CCPHYSICS_WORLD_H__ - -#include - -#include "cocoa/CCObject.h" -#include "cocoa/CCGeometry.h" - - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) -typedef struct cpArbiter cpArbiter; -typedef struct cpSpace cpSpace; -#endif - -NS_CC_BEGIN - -class PhysicsBody; -class PhysicsJoint; -class PhysicsWorldInfo; -class PhysicsShape; -class PhysicsContact; -class PhysicsContactPreSolve; -class PhysicsContactPostSolve; -class PhysicsContactListener; -class Array; - -class Sprite; -class Scene; -class DrawNode; - -/** - * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object. - */ -class PhysicsWorld -{ -public: - /** Adds a joint to the physics world.*/ - void addJoint(PhysicsJoint* joint); - /** Removes a joint from the physics world.*/ - void removeJoint(PhysicsJoint* joint); - /** Remove all joints from the physics world.*/ - void removeAllJoints(); - - Array* getBodysAlongRay(Point start, Point end) const; - Array* getBodysAtPoint(Point point) const; - Array* getBodysInRect(Rect rect) const; - Array* getAllBody() const; - - /** Register a listener to receive contact callbacks*/ - inline void registerContactListener(PhysicsContactListener* delegate) { _listener = delegate; } - /** Unregister a listener. */ - inline void unregisterContactListener() { _listener = nullptr; } - - /** get the gravity value */ - inline Point getGravity() { return _gravity; } - /** set the gravity value */ - void setGravity(Point gravity); - - /** test the debug draw is enabled */ - inline bool isDebugDraw() { return _debugDraw; } - /** set the debug draw */ - inline void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } - - virtual void removeBody(PhysicsBody* body); - virtual void removeBodyByTag(int tag); - -protected: - static PhysicsWorld* create(); - bool init(); - - void setScene(Scene* scene); - - virtual void addBody(PhysicsBody* body); - virtual void addShape(PhysicsShape* shape); - virtual void removeShape(PhysicsShape* shape); - virtual void update(float delta); - - virtual void debugDraw(); - virtual void drawWithShape(DrawNode* node, PhysicsShape* shape); - - - virtual int collisionBeginCallback(PhysicsContact& contact); - virtual int collisionPreSolveCallback(PhysicsContact& contact, const PhysicsContactPreSolve& solve); - virtual void collisionPostSolveCallback(PhysicsContact& contact, const PhysicsContactPostSolve& solve); - virtual void collisionSeparateCallback(PhysicsContact& contact); - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - static int collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, void *data); - static int collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); - static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, void *data); -#endif - -protected: - Point _gravity; - float _speed; - PhysicsWorldInfo* _info; - PhysicsContactListener* _listener; - - - Array* _bodys; - std::list _joints; - Scene* _scene; - - bool _debugDraw; - DrawNode* _drawNode; - -protected: - PhysicsWorld(); - virtual ~PhysicsWorld(); - - friend class Sprite; - friend class Scene; - friend class PhysicsBody; - friend class PhysicsShape; -}; - -NS_CC_END - -#endif // __CCPHYSICS_WORLD_H__ - -#endif // CC_USE_PHYSICS diff --git a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h deleted file mode 100644 index a394aa807b..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsBodyInfo.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_BODY_INFO_H__ -#define __CCPHYSICS_BODY_INFO_H__ -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCObject.h" - -NS_CC_BEGIN - -class PhysicsBodyInfo : public Clonable -{ -public: - cpBody* body; - cpGroup group; - -private: - PhysicsBodyInfo(); - ~PhysicsBodyInfo(); - - Clonable* clone() const override; - - friend class PhysicsBody; -}; - -NS_CC_END -#endif // __CCPHYSICS_BODY_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h b/cocos2dx/physics/chipmunk/CCPhysicsHelper.h deleted file mode 100644 index 9334d87124..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsHelper.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_HELPER_H__ -#define __CCPHYSICS_HELPER_H__ - -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include "cocoa/CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsHelper -{ -public: - static Point cpv2point(const cpVect& vec) { return Point(vec.x, vec.y); } - static cpVect point2cpv(const Point& point) { return cpv(point.x, point.y); } - static Size cpv2size(const cpVect& vec) { return Size(vec.x, vec.y); } - static cpVect size2cpv(const Size& size) { return cpv(size.width, size.height); } - static float cpfloat2float(cpFloat f) { return f; } - static cpFloat float2cpfloat(float f) { return f; } - - static Point* cpvs2points(const cpVect* cpvs, Point* points, int count) - { - for (int i = 0; i < count; ++i) - { - points[i] = cpv2point(cpvs[i]); - } - - return points; - } - - static cpVect* points2cpvs(const Point* points, cpVect* cpvs, int count) - { - for (int i = 0; i < count; ++i) - { - cpvs[i] = point2cpv(points[i]); - } - - return cpvs; - } -}; - -NS_CC_END -#endif // __CCPHYSICS_HELPER_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h deleted file mode 100644 index 1140b8783e..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsJointInfo.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_JOINT_INFO_H__ -#define __CCPHYSICS_JOINT_INFO_H__ -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" -#include -#include -NS_CC_BEGIN - -class PhysicsJoint; - -class PhysicsJointInfo -{ -public: - void add(cpConstraint* shape); - void remove(cpConstraint* shape); - void removeAll(); - -public: - std::vector joints; - PhysicsJoint* joint; - static std::map map; - -private: - PhysicsJointInfo(PhysicsJoint* joint); - ~PhysicsJointInfo(); - - friend class PhysicsJoint; -}; - -NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h b/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h deleted file mode 100644 index f84f8613c6..0000000000 --- a/cocos2dx/physics/chipmunk/CCPhysicsShapeInfo.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 cocos2d-x.org - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -#ifndef __CCPHYSICS_SHAPE_INFO_H__ -#define __CCPHYSICS_SHAPE_INFO_H__ - -#include -#include -#include "chipmunk.h" -#include "platform/CCPlatformMacros.h" - -NS_CC_BEGIN - -class PhysicsShape; - -class PhysicsShapeInfo -{ -public: - void add(cpShape* shape); - void remove(cpShape* shape); - void removeAll(); - void setGroup(cpGroup group); - void setBody(cpBody* body); - -public: - std::vector shapes; - PhysicsShape* shape; - cpBody* body; - cpGroup group; - static std::map map; - static cpBody* shareBody; - -private: - PhysicsShapeInfo(PhysicsShape* shape); - ~PhysicsShapeInfo(); - - friend class PhysicsShape; -}; - -NS_CC_END -#endif // __CCPHYSICS_SHAPE_INFO_H__ - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos2dx/sprite_nodes/CCSprite.cpp b/cocos2dx/sprite_nodes/CCSprite.cpp deleted file mode 100644 index f9bb30df89..0000000000 --- a/cocos2dx/sprite_nodes/CCSprite.cpp +++ /dev/null @@ -1,1138 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2011 Zynga Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ - -#include "CCSpriteBatchNode.h" -#include -#include -#include "CCAnimation.h" -#include "CCAnimationCache.h" -#include "ccConfig.h" -#include "CCSprite.h" -#include "CCSpriteFrame.h" -#include "CCSpriteFrameCache.h" -#include "textures/CCTextureCache.h" -#include "draw_nodes/CCDrawingPrimitives.h" -#include "shaders/CCShaderCache.h" -#include "shaders/ccGLStateCache.h" -#include "shaders/CCGLProgram.h" -#include "CCDirector.h" -#include "cocoa/CCGeometry.h" -#include "textures/CCTexture2D.h" -#include "cocoa/CCAffineTransform.h" -#include "support/TransformUtils.h" -#include "support/CCProfiling.h" -// external -#include "kazmath/GL/matrix.h" - - -using namespace std; - -NS_CC_BEGIN - -#if CC_SPRITEBATCHNODE_RENDER_SUBPIXEL -#define RENDER_IN_SUBPIXEL -#else -#define RENDER_IN_SUBPIXEL(__ARGS__) (ceil(__ARGS__)) -#endif - -Sprite* Sprite::createWithTexture(Texture2D *texture) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithTexture(texture)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithTexture(texture, rect)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::create(const char *filename) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithFile(filename)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::create(const char *filename, const Rect& rect) -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithFile(filename, rect)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame) -{ - Sprite *sprite = new Sprite(); - if (spriteFrame && sprite && sprite->initWithSpriteFrame(spriteFrame)) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) -{ - SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); - -#if COCOS2D_DEBUG > 0 - char msg[256] = {0}; - sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); - CCASSERT(frame != NULL, msg); -#endif - - return createWithSpriteFrame(frame); -} - -Sprite* Sprite::create() -{ - Sprite *sprite = new Sprite(); - if (sprite && sprite->init()) - { - sprite->autorelease(); - return sprite; - } - CC_SAFE_DELETE(sprite); - return NULL; -} - -bool Sprite::init(void) -{ - return initWithTexture(NULL, Rect::ZERO); -} - -// designated initializer -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) -{ - if (NodeRGBA::init()) - { - _batchNode = NULL; - - _recursiveDirty = false; - setDirty(false); - - _opacityModifyRGB = true; - - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - - _flippedX = _flippedY = false; - - // default transform anchor: center - setAnchorPoint(Point(0.5f, 0.5f)); - - // zwoptex default values - _offsetPosition = Point::ZERO; - - _hasChildren = false; - - // clean the Quad - memset(&_quad, 0, sizeof(_quad)); - - // Atlas: Color - _quad.bl.colors = Color4B::WHITE; - _quad.br.colors = Color4B::WHITE; - _quad.tl.colors = Color4B::WHITE; - _quad.tr.colors = Color4B::WHITE; - - // shader program - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); - - // update texture (calls updateBlendFunc) - setTexture(texture); - setTextureRect(rect, rotated, rect.size); - - // by default use "Self Render". - // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" - setBatchNode(NULL); - - return true; - } - else - { - return false; - } -} - -bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect) -{ - return initWithTexture(texture, rect, false); -} - -bool Sprite::initWithTexture(Texture2D *texture) -{ - CCASSERT(texture != NULL, "Invalid texture for sprite"); - - Rect rect = Rect::ZERO; - rect.size = texture->getContentSize(); - - return initWithTexture(texture, rect); -} - -bool Sprite::initWithFile(const char *filename) -{ - CCASSERT(filename != NULL, "Invalid filename for sprite"); - - Texture2D *texture = TextureCache::getInstance()->addImage(filename); - if (texture) - { - Rect rect = Rect::ZERO; - rect.size = texture->getContentSize(); - return initWithTexture(texture, rect); - } - - // don't release here. - // when load texture failed, it's better to get a "transparent" sprite then a crashed program - // this->release(); - return false; -} - -bool Sprite::initWithFile(const char *filename, const Rect& rect) -{ - CCASSERT(filename != NULL, ""); - - Texture2D *texture = TextureCache::getInstance()->addImage(filename); - if (texture) - { - return initWithTexture(texture, rect); - } - - // don't release here. - // when load texture failed, it's better to get a "transparent" sprite then a crashed program - // this->release(); - return false; -} - -bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) -{ - CCASSERT(spriteFrame != NULL, ""); - - bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect()); - setDisplayFrame(spriteFrame); - - return bRet; -} - -bool Sprite::initWithSpriteFrameName(const char *spriteFrameName) -{ - CCASSERT(spriteFrameName != NULL, ""); - - SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); - return initWithSpriteFrame(frame); -} - -// XXX: deprecated -/* -Sprite* Sprite::initWithCGImage(CGImageRef pImage) -{ - // todo - // because it is deprecated, so we do not implement it - - return NULL; -} -*/ - -/* -Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey) -{ - CCASSERT(pImage != NULL); - - // XXX: possible bug. See issue #349. New API should be added - Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey); - - const Size& size = texture->getContentSize(); - Rect rect = Rect(0 ,0, size.width, size.height); - - return initWithTexture(texture, rect); -} -*/ - -Sprite::Sprite(void) -: _shouldBeHidden(false) -, _texture(nullptr) -{ -} - -Sprite::~Sprite(void) -{ - CC_SAFE_RELEASE(_texture); -} - -void Sprite::setTextureRect(const Rect& rect) -{ - setTextureRect(rect, false, rect.size); -} - - -void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) -{ - _rectRotated = rotated; - - setContentSize(untrimmedSize); - setVertexRect(rect); - setTextureCoords(rect); - - Point relativeOffset = _unflippedOffsetPositionFromCenter; - - // issue #732 - if (_flippedX) - { - relativeOffset.x = -relativeOffset.x; - } - if (_flippedY) - { - relativeOffset.y = -relativeOffset.y; - } - - _offsetPosition.x = relativeOffset.x + (_contentSize.width - _rect.size.width) / 2; - _offsetPosition.y = relativeOffset.y + (_contentSize.height - _rect.size.height) / 2; - - // rendering using batch node - if (_batchNode) - { - // update dirty_, don't update recursiveDirty_ - setDirty(true); - } - else - { - // self rendering - - // Atlas: Vertex - float x1 = 0 + _offsetPosition.x; - float y1 = 0 + _offsetPosition.y; - float x2 = x1 + _rect.size.width; - float y2 = y1 + _rect.size.height; - - // Don't update Z. - _quad.bl.vertices = Vertex3F(x1, y1, 0); - _quad.br.vertices = Vertex3F(x2, y1, 0); - _quad.tl.vertices = Vertex3F(x1, y2, 0); - _quad.tr.vertices = Vertex3F(x2, y2, 0); - } -} - -// override this method to generate "double scale" sprites -void Sprite::setVertexRect(const Rect& rect) -{ - _rect = rect; -} - -void Sprite::setTextureCoords(Rect rect) -{ - rect = CC_RECT_POINTS_TO_PIXELS(rect); - - Texture2D *tex = _batchNode ? _textureAtlas->getTexture() : _texture; - if (! tex) - { - return; - } - - float atlasWidth = (float)tex->getPixelsWide(); - float atlasHeight = (float)tex->getPixelsHigh(); - - float left, right, top, bottom; - - if (_rectRotated) - { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left+(rect.size.height*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top+(rect.size.width*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = (rect.origin.x+rect.size.height) / atlasWidth; - top = rect.origin.y/atlasHeight; - bottom = (rect.origin.y+rect.size.width) / atlasHeight; -#endif // CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if (_flippedX) - { - CC_SWAP(top, bottom, float); - } - - if (_flippedY) - { - CC_SWAP(left, right, float); - } - - _quad.bl.texCoords.u = left; - _quad.bl.texCoords.v = top; - _quad.br.texCoords.u = left; - _quad.br.texCoords.v = bottom; - _quad.tl.texCoords.u = right; - _quad.tl.texCoords.v = top; - _quad.tr.texCoords.u = right; - _quad.tr.texCoords.v = bottom; - } - else - { -#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - left = (2*rect.origin.x+1)/(2*atlasWidth); - right = left + (rect.size.width*2-2)/(2*atlasWidth); - top = (2*rect.origin.y+1)/(2*atlasHeight); - bottom = top + (rect.size.height*2-2)/(2*atlasHeight); -#else - left = rect.origin.x/atlasWidth; - right = (rect.origin.x + rect.size.width) / atlasWidth; - top = rect.origin.y/atlasHeight; - bottom = (rect.origin.y + rect.size.height) / atlasHeight; -#endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL - - if(_flippedX) - { - CC_SWAP(left,right,float); - } - - if(_flippedY) - { - CC_SWAP(top,bottom,float); - } - - _quad.bl.texCoords.u = left; - _quad.bl.texCoords.v = bottom; - _quad.br.texCoords.u = right; - _quad.br.texCoords.v = bottom; - _quad.tl.texCoords.u = left; - _quad.tl.texCoords.v = top; - _quad.tr.texCoords.u = right; - _quad.tr.texCoords.v = top; - } -} - -void Sprite::updateTransform(void) -{ - CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode"); - -#ifdef CC_USE_PHYSICS - updatePhysicsTransform(); - setDirty(true); -#endif - - // recalculate matrix only if it is dirty - if( isDirty() ) { - - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if( !_visible || ( _parent && _parent != _batchNode && static_cast(_parent)->_shouldBeHidden) ) - { - _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0); - _shouldBeHidden = true; - } - else - { - _shouldBeHidden = false; - - if( ! _parent || _parent == _batchNode ) - { - _transformToBatch = getNodeToParentTransform(); - } - else - { - CCASSERT( dynamic_cast(_parent), "Logic error in Sprite. Parent must be a Sprite"); - _transformToBatch = AffineTransformConcat( getNodeToParentTransform() , static_cast(_parent)->_transformToBatch ); - } - - // - // calculate the Quad based on the Affine Matrix - // - - Size size = _rect.size; - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - - float x2 = x1 + size.width; - float y2 = y1 + size.height; - float x = _transformToBatch.tx; - float y = _transformToBatch.ty; - - float cr = _transformToBatch.a; - float sr = _transformToBatch.b; - float cr2 = _transformToBatch.d; - float sr2 = -_transformToBatch.c; - float ax = x1 * cr - y1 * sr2 + x; - float ay = x1 * sr + y1 * cr2 + y; - - float bx = x2 * cr - y1 * sr2 + x; - float by = x2 * sr + y1 * cr2 + y; - - float cx = x2 * cr - y2 * sr2 + x; - float cy = x2 * sr + y2 * cr2 + y; - - float dx = x1 * cr - y2 * sr2 + x; - float dy = x1 * sr + y2 * cr2 + y; - - _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _vertexZ ); - _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _vertexZ ); - _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _vertexZ ); - _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _vertexZ ); - } - - // MARMALADE CHANGE: ADDED CHECK FOR NULL, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS - if (_textureAtlas) - { - _textureAtlas->updateQuad(&_quad, _atlasIndex); - } - - _recursiveDirty = false; - setDirty(false); - } - - // MARMALADE CHANGED - // recursively iterate over children -/* if( _hasChildren ) - { - // MARMALADE: CHANGED TO USE Node* - // NOTE THAT WE HAVE ALSO DEFINED virtual Node::updateTransform() - arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*); - }*/ - Node::updateTransform(); - -#if CC_SPRITE_DEBUG_DRAW - // draw bounding box - Point vertices[4] = { - Point( _quad.bl.vertices.x, _quad.bl.vertices.y ), - Point( _quad.br.vertices.x, _quad.br.vertices.y ), - Point( _quad.tr.vertices.x, _quad.tr.vertices.y ), - Point( _quad.tl.vertices.x, _quad.tl.vertices.y ), - }; - ccDrawPoly(vertices, 4, true); -#endif // CC_SPRITE_DEBUG_DRAW -} - -// draw - -void Sprite::draw(void) -{ - CC_PROFILER_START_CATEGORY(kProfilerCategorySprite, "CCSprite - draw"); - - CCASSERT(!_batchNode, "If Sprite is being rendered by SpriteBatchNode, Sprite#draw SHOULD NOT be called"); - - CC_NODE_DRAW_SETUP(); - - GL::blendFunc( _blendFunc.src, _blendFunc.dst ); - - GL::bindTexture2D( _texture->getName() ); - GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); - -#define kQuadSize sizeof(_quad.bl) -#ifdef EMSCRIPTEN - long offset = 0; - setGLBufferData(&_quad, 4 * kQuadSize, 0); -#else - long offset = (long)&_quad; -#endif // EMSCRIPTEN - - // vertex - int diff = offsetof( V3F_C4B_T2F, vertices); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); - - // texCoods - diff = offsetof( V3F_C4B_T2F, texCoords); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); - - // color - diff = offsetof( V3F_C4B_T2F, colors); - glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); - - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - CHECK_GL_ERROR_DEBUG(); - - -#if CC_SPRITE_DEBUG_DRAW == 1 - // draw bounding box - Point vertices[4]={ - Point(_quad.tl.vertices.x,_quad.tl.vertices.y), - Point(_quad.bl.vertices.x,_quad.bl.vertices.y), - Point(_quad.br.vertices.x,_quad.br.vertices.y), - Point(_quad.tr.vertices.x,_quad.tr.vertices.y), - }; - ccDrawPoly(vertices, 4, true); -#elif CC_SPRITE_DEBUG_DRAW == 2 - // draw texture box - Size s = this->getTextureRect().size; - Point offsetPix = this->getOffsetPosition(); - Point vertices[4] = { - Point(offsetPix.x,offsetPix.y), Point(offsetPix.x+s.width,offsetPix.y), - Point(offsetPix.x+s.width,offsetPix.y+s.height), Point(offsetPix.x,offsetPix.y+s.height) - }; - ccDrawPoly(vertices, 4, true); -#endif // CC_SPRITE_DEBUG_DRAW - - CC_INCREMENT_GL_DRAWS(1); - - CC_PROFILER_STOP_CATEGORY(kProfilerCategorySprite, "CCSprite - draw"); -} - -// Node overrides - -void Sprite::addChild(Node* child) -{ - Node::addChild(child); -} - -void Sprite::addChild(Node *child, int zOrder) -{ - Node::addChild(child, zOrder); -} - -void Sprite::addChild(Node *child, int zOrder, int tag) -{ - CCASSERT(child != NULL, "Argument must be non-NULL"); - - if (_batchNode) - { - Sprite* childSprite = dynamic_cast(child); - CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode"); - CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), ""); - //put it in descendants array of batch node - _batchNode->appendChild(childSprite); - - if (!_reorderChildDirty) - { - setReorderChildDirtyRecursively(); - } - } - //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check - Node::addChild(child, zOrder, tag); - _hasChildren = true; -} - -void Sprite::reorderChild(Node *child, int zOrder) -{ - CCASSERT(child != NULL, ""); - CCASSERT(_children->containsObject(child), ""); - - if (zOrder == child->getZOrder()) - { - return; - } - - if( _batchNode && ! _reorderChildDirty) - { - setReorderChildDirtyRecursively(); - _batchNode->reorderBatch(true); - } - - Node::reorderChild(child, zOrder); -} - -void Sprite::removeChild(Node *child, bool cleanup) -{ - if (_batchNode) - { - _batchNode->removeSpriteFromAtlas((Sprite*)(child)); - } - - Node::removeChild(child, cleanup); - -} - -void Sprite::removeAllChildrenWithCleanup(bool cleanup) -{ - if (_batchNode) - { - Object* object = NULL; - CCARRAY_FOREACH(_children, object) - { - Sprite* child = dynamic_cast(object); - if (child) - { - _batchNode->removeSpriteFromAtlas(child); - } - } - } - - Node::removeAllChildrenWithCleanup(cleanup); - - _hasChildren = false; -} - -void Sprite::sortAllChildren() -{ - if (_reorderChildDirty) - { -#if 0 - int i = 0, j = 0, length = _children->count(); - - // insertion sort - for(i=1; i( _children->getObjectAtIndex(i) ); - auto tempJ = static_cast( _children->getObjectAtIndex(j) ); - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() || - ( tempI->getZOrder() == tempJ->getZOrder() && - tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) ) - { - _children->fastSetObject( tempJ, j+1 ); - j = j-1; - if(j>=0) - tempJ = static_cast( _children->getObjectAtIndex(j) ); - } - _children->fastSetObject(tempI, j+1); - } -#else - std::sort(std::begin(*_children), std::end(*_children), nodeComparisonLess); -#endif - - if ( _batchNode) - { - arrayMakeObjectsPerformSelector(_children, sortAllChildren, Sprite*); - } - - _reorderChildDirty = false; - } -} - -// -// Node property overloads -// used only when parent is SpriteBatchNode -// - -void Sprite::setReorderChildDirtyRecursively(void) -{ - //only set parents flag the first time - if ( ! _reorderChildDirty ) - { - _reorderChildDirty = true; - Node* node = static_cast(_parent); - while (node && node != _batchNode) - { - static_cast(node)->setReorderChildDirtyRecursively(); - node=node->getParent(); - } - } -} - - -void Sprite::setDirtyRecursively(bool bValue) -{ - _recursiveDirty = bValue; - setDirty(bValue); - // recursively set dirty - if (_hasChildren) - { - Object* object = NULL; - CCARRAY_FOREACH(_children, object) - { - Sprite* child = dynamic_cast(object); - if (child) - { - child->setDirtyRecursively(true); - } - } - } -} - -// XXX HACK: optimization -#define SET_DIRTY_RECURSIVELY() { \ - if (_batchNode && ! _recursiveDirty) { \ - _recursiveDirty = true; \ - setDirty(true); \ - if ( _hasChildren) \ - setDirtyRecursively(true); \ - } \ - } - -void Sprite::setPosition(const Point& pos) -{ - Node::setPosition(pos); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotation(float rotation) -{ - Node::setRotation(rotation); - - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotationX(float fRotationX) -{ - Node::setRotationX(fRotationX); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setRotationY(float fRotationY) -{ - Node::setRotationY(fRotationY); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setSkewX(float sx) -{ - Node::setSkewX(sx); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setSkewY(float sy) -{ - Node::setSkewY(sy); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScaleX(float scaleX) -{ - Node::setScaleX(scaleX); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScaleY(float scaleY) -{ - Node::setScaleY(scaleY); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setScale(float fScale) -{ - Node::setScale(fScale); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setVertexZ(float fVertexZ) -{ - Node::setVertexZ(fVertexZ); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setAnchorPoint(const Point& anchor) -{ - Node::setAnchorPoint(anchor); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::ignoreAnchorPointForPosition(bool value) -{ - CCASSERT(! _batchNode, "ignoreAnchorPointForPosition is invalid in Sprite"); - Node::ignoreAnchorPointForPosition(value); -} - -void Sprite::setVisible(bool bVisible) -{ - Node::setVisible(bVisible); - SET_DIRTY_RECURSIVELY(); -} - -void Sprite::setFlippedX(bool flippedX) -{ - if (_flippedX != flippedX) - { - _flippedX = flippedX; - setTextureRect(_rect, _rectRotated, _contentSize); - } -} - -bool Sprite::isFlippedX(void) const -{ - return _flippedX; -} - -void Sprite::setFlippedY(bool flippedY) -{ - if (_flippedY != flippedY) - { - _flippedY = flippedY; - setTextureRect(_rect, _rectRotated, _contentSize); - } -} - -bool Sprite::isFlippedY(void) const -{ - return _flippedY; -} - -// -// RGBA protocol -// - -void Sprite::updateColor(void) -{ - Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); - - // special opacity for premultiplied textures - if (_opacityModifyRGB) - { - color4.r *= _displayedOpacity/255.0f; - color4.g *= _displayedOpacity/255.0f; - color4.b *= _displayedOpacity/255.0f; - } - - _quad.bl.colors = color4; - _quad.br.colors = color4; - _quad.tl.colors = color4; - _quad.tr.colors = color4; - - // renders using batch node - if (_batchNode) - { - if (_atlasIndex != INDEX_NOT_INITIALIZED) - { - _textureAtlas->updateQuad(&_quad, _atlasIndex); - } - else - { - // no need to set it recursively - // update dirty_, don't update recursiveDirty_ - setDirty(true); - } - } - - // self render - // do nothing -} - -void Sprite::setOpacity(GLubyte opacity) -{ - NodeRGBA::setOpacity(opacity); - - updateColor(); -} - -void Sprite::setColor(const Color3B& color3) -{ - NodeRGBA::setColor(color3); - - updateColor(); -} - -void Sprite::setOpacityModifyRGB(bool modify) -{ - if (_opacityModifyRGB != modify) - { - _opacityModifyRGB = modify; - updateColor(); - } -} - -bool Sprite::isOpacityModifyRGB(void) const -{ - return _opacityModifyRGB; -} - -void Sprite::updateDisplayedColor(const Color3B& parentColor) -{ - NodeRGBA::updateDisplayedColor(parentColor); - - updateColor(); -} - -void Sprite::updateDisplayedOpacity(GLubyte opacity) -{ - NodeRGBA::updateDisplayedOpacity(opacity); - - updateColor(); -} - -// Frames - -void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) -{ - _unflippedOffsetPositionFromCenter = pNewFrame->getOffset(); - - Texture2D *pNewTexture = pNewFrame->getTexture(); - // update texture before updating texture rect - if (pNewTexture != _texture) - { - setTexture(pNewTexture); - } - - // update rect - _rectRotated = pNewFrame->isRotated(); - setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); -} - -void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int frameIndex) -{ - CCASSERT(animationName, "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); - - Animation *a = AnimationCache::getInstance()->getAnimation(animationName); - - CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - - AnimationFrame* frame = static_cast( a->getFrames()->getObjectAtIndex(frameIndex) ); - - CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); - - setDisplayFrame(frame->getSpriteFrame()); -} - -bool Sprite::isFrameDisplayed(SpriteFrame *frame) const -{ - Rect r = frame->getRect(); - - return (r.equals(_rect) && - frame->getTexture()->getName() == _texture->getName() && - frame->getOffset().equals(_unflippedOffsetPositionFromCenter)); -} - -SpriteFrame* Sprite::getDisplayFrame() -{ - return SpriteFrame::createWithTexture(_texture, - CC_RECT_POINTS_TO_PIXELS(_rect), - _rectRotated, - CC_POINT_POINTS_TO_PIXELS(_unflippedOffsetPositionFromCenter), - CC_SIZE_POINTS_TO_PIXELS(_contentSize)); -} - -SpriteBatchNode* Sprite::getBatchNode() -{ - return _batchNode; -} - -void Sprite::setBatchNode(SpriteBatchNode *spriteBatchNode) -{ - _batchNode = spriteBatchNode; // weak reference - - // self render - if( ! _batchNode ) { - _atlasIndex = INDEX_NOT_INITIALIZED; - setTextureAtlas(NULL); - _recursiveDirty = false; - setDirty(false); - - float x1 = _offsetPosition.x; - float y1 = _offsetPosition.y; - float x2 = x1 + _rect.size.width; - float y2 = y1 + _rect.size.height; - _quad.bl.vertices = Vertex3F( x1, y1, 0 ); - _quad.br.vertices = Vertex3F( x2, y1, 0 ); - _quad.tl.vertices = Vertex3F( x1, y2, 0 ); - _quad.tr.vertices = Vertex3F( x2, y2, 0 ); - - } else { - - // using batch - _transformToBatch = AffineTransformIdentity; - setTextureAtlas(_batchNode->getTextureAtlas()); // weak ref - } -} - -// Texture protocol - -void Sprite::updateBlendFunc(void) -{ - CCASSERT(! _batchNode, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode"); - - // it is possible to have an untextured sprite - if (! _texture || ! _texture->hasPremultipliedAlpha()) - { - _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED; - setOpacityModifyRGB(false); - } - else - { - _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; - setOpacityModifyRGB(true); - } -} - -/* - * This array is the data of a white image with 2 by 2 dimension. - * It's used for creating a default texture when sprite's texture is set to NULL. - * Supposing codes as follows: - * - * auto sp = new Sprite(); - * sp->init(); // Texture was set to NULL, in order to make opacity and color to work correctly, we need to create a 2x2 white texture. - * - * The test is in "TestCpp/SpriteTest/Sprite without texture". - */ -static unsigned char cc_2x2_white_image[] = { - // RGBA8888 - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF -}; - -#define CC_2x2_WHITE_IMAGE_KEY "/cc_2x2_white_image" - -void Sprite::setTexture(Texture2D *texture) -{ - // If batchnode, then texture id should be the same - CCASSERT(! _batchNode || texture->getName() == _batchNode->getTexture()->getName(), "CCSprite: Batched sprites should use the same texture as the batchnode"); - // accept texture==nil as argument - CCASSERT( !texture || dynamic_cast(texture), "setTexture expects a Texture2D. Invalid argument"); - - if (NULL == texture) - { - // Gets the texture by key firstly. - texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); - - // If texture wasn't in cache, create it from RAW data. - if (NULL == texture) - { - Image* image = new Image(); - bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8); - CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully."); - - texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY); - CC_SAFE_RELEASE(image); - } - } - - if (!_batchNode && _texture != texture) - { - CC_SAFE_RETAIN(texture); - CC_SAFE_RELEASE(_texture); - _texture = texture; - updateBlendFunc(); - } -} - -Texture2D* Sprite::getTexture(void) const -{ - return _texture; -} - -NS_CC_END