From d590986e730ec25ab2b0ea8193f42bf521368732 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 13 Nov 2013 15:55:36 -0800 Subject: [PATCH 01/75] Constructors are protected --- cocos/2d/CCLabel.cpp | 10 +- cocos/2d/CCLabelBMFont.cpp | 8 +- cocos/2d/CCLayer.h | 76 +++--- cocos/2d/CCNode.h | 47 ++-- cocos/2d/CCScene.h | 28 +-- cocos/2d/CCSprite.cpp | 24 +- cocos/2d/CCSprite.h | 228 +++++++++--------- cocos/2d/CCTMXLayer.cpp | 8 +- cocos/2d/CCTransition.cpp | 1 - cocos/2d/ccMacros.h | 18 ++ cocos/gui/UIButton.cpp | 12 +- cocos/gui/UICheckBox.cpp | 20 +- cocos/gui/UIImageView.cpp | 4 +- cocos/gui/UILayout.cpp | 4 +- cocos/gui/UILoadingBar.cpp | 4 +- cocos/gui/UISlider.cpp | 20 +- .../GUI/CCControlExtension/CCScale9Sprite.cpp | 73 +++--- .../Classes/ActionsTest/ActionsTest.cpp | 9 - .../TestCpp/Classes/ActionsTest/ActionsTest.h | 98 ++++++++ .../ClippingNodeTest/ClippingNodeTest.cpp | 9 - .../ClippingNodeTest/ClippingNodeTest.h | 34 +++ .../ConfigurationTest/ConfigurationTest.cpp | 11 +- .../ConfigurationTest/ConfigurationTest.h | 10 + .../Scale9SpriteTest/Scale9SpriteTest.cpp | 9 - .../Scale9SpriteTest/Scale9SpriteTest.h | 28 +++ .../Classes/FileUtilsTest/FileUtilsTest.cpp | 9 - .../Classes/FileUtilsTest/FileUtilsTest.h | 10 + .../NewEventDispatcherTest.cpp | 18 +- .../PerformanceTest/PerformanceAllocTest.cpp | 7 +- .../PerformanceTest/PerformanceAllocTest.h | 10 + .../PerformanceNodeChildrenTest.h | 34 +++ .../Classes/PhysicsTest/PhysicsTest.cpp | 9 - .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 28 ++- .../Classes/SchedulerTest/SchedulerTest.cpp | 15 +- .../Classes/SchedulerTest/SchedulerTest.h | 53 +++- .../Classes/ShaderTest/ShaderTest2.cpp | 23 +- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- samples/Cpp/TestCpp/Classes/testBasic.cpp | 19 +- samples/Cpp/TestCpp/Classes/testBasic.h | 2 +- 39 files changed, 614 insertions(+), 418 deletions(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 0dc7fc5081..45fbbeb5e6 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -119,16 +119,16 @@ Label::~Label() if (_fontAtlas) FontAtlasCache::releaseFontAtlas(_fontAtlas); - delete _reusedLetter; + _reusedLetter->release(); } bool Label::init() { if(_fontAtlas) { - _reusedLetter = new Sprite; - _reusedLetter->initWithTexture(&_fontAtlas->getTexture(0)); + _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); + _reusedLetter->retain(); return SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); } @@ -437,15 +437,13 @@ Sprite * Label::getLetter(int ID) uvRect.origin.x = _lettersInfo[ID].def.U; uvRect.origin.y = _lettersInfo[ID].def.V; - sp = new Sprite(); - sp->initWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); + sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID), uvRect); sp->setBatchNode(this); sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); sp->setPosition(_lettersInfo[ID].position); sp->setOpacity(_realOpacity); this->addSpriteWithoutQuad(sp, ID, ID); - sp->release(); } return sp; } diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 6749c5d107..c004cabd0f 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -511,8 +511,8 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string _imageOffset = imageOffset; - _reusedChar = new Sprite(); - _reusedChar->initWithTexture(_textureAtlas->getTexture(), Rect(0, 0, 0, 0), false); + _reusedChar = Sprite::createWithTexture(_textureAtlas->getTexture(), Rect(0, 0, 0, 0)); + _reusedChar->retain(); _reusedChar->setBatchNode(this); this->setString(theString, true); @@ -663,10 +663,8 @@ void LabelBMFont::createFontChars() } else { - fontChar = new Sprite(); - fontChar->initWithTexture(_textureAtlas->getTexture(), rect); + fontChar = Sprite::createWithTexture(_textureAtlas->getTexture(), rect); addChild(fontChar, i, i); - fontChar->release(); } // Apply label properties diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 2aafa9a895..6120428c32 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -59,18 +59,8 @@ class CC_DLL Layer : public Node { public: /** creates a fullscreen black layer */ - static Layer *create(void); - /** - * @js ctor - */ - Layer(); - /** - * @js NA - * @lua NA - */ - virtual ~Layer(); - virtual bool init(); - + static Layer *create(); + // Deprecated touch callbacks. CC_DEPRECATED_ATTRIBUTE virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; CC_DEPRECATED_ATTRIBUTE virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} @@ -109,9 +99,14 @@ public: /** @deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead. */ CC_DEPRECATED_ATTRIBUTE virtual void keyBackClicked() final {}; CC_DEPRECATED_ATTRIBUTE virtual void keyMenuClicked() final {}; - // - // Overrides - // + +protected: + Layer(); + virtual ~Layer(); + virtual bool init(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Layer); }; #ifdef __apple__ @@ -130,17 +125,7 @@ class CC_DLL LayerRGBA : public Layer, public RGBAProtocol { public: CREATE_FUNC(LayerRGBA); - /** - * @js ctor - */ - LayerRGBA(); - /** - * @js NA - * @lua NA - */ - virtual ~LayerRGBA(); - - virtual bool init(); + // // Overrides @@ -161,10 +146,18 @@ public: virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);} virtual bool isOpacityModifyRGB() const override { return false; } + protected: + LayerRGBA(); + virtual ~LayerRGBA(); + virtual bool init(); + GLubyte _displayedOpacity, _realOpacity; Color3B _displayedColor, _realColor; bool _cascadeOpacityEnabled, _cascadeColorEnabled; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(LayerRGBA); }; // @@ -188,27 +181,6 @@ public: static LayerColor * create(const Color4B& color, GLfloat width, GLfloat height); /** creates a Layer with color. Width and height are the window size. */ static LayerColor * create(const Color4B& color); - /** - * @js ctor - */ - LayerColor(); - /** - * @js NA - * @lua NA - */ - virtual ~LayerColor(); - - virtual bool init(); - /** initializes a Layer with color, width and height in Points - * @js init - * @lua init - */ - bool initWithColor(const Color4B& color, GLfloat width, GLfloat height); - /** initializes a Layer with color. Width and height are the window size. - * @js init - * @lua init - */ - bool initWithColor(const Color4B& color); /** change width in Points*/ void changeWidth(GLfloat w); @@ -242,11 +214,21 @@ public: virtual void setBlendFunc(const BlendFunc& blendFunc) override; protected: + LayerColor(); + virtual ~LayerColor(); + virtual bool init(); + bool initWithColor(const Color4B& color, GLfloat width, GLfloat height); + bool initWithColor(const Color4B& color); + virtual void updateColor(); BlendFunc _blendFunc; Vertex2F _squareVertices[4]; Color4F _squareColors[4]; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(LayerColor); + }; // diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 5a363c8053..65f94f565d 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -152,25 +152,6 @@ public: */ 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' @@ -1413,7 +1394,11 @@ public: #endif protected: - + // Nodes should be created using create(); + Node(); + virtual ~Node(); + virtual bool init(); + /// lazy allocs void childrenAlloc(void); @@ -1496,6 +1481,9 @@ protected: #ifdef CC_USE_PHYSICS PhysicsBody* _physicsBody; ///< the physicsBody the node have #endif + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Node); }; //#pragma mark - NodeRGBA @@ -1512,18 +1500,6 @@ protected: 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; @@ -1543,12 +1519,19 @@ public: virtual bool isOpacityModifyRGB() const override { return false; }; protected: + NodeRGBA(); + virtual ~NodeRGBA(); + virtual bool init(); + GLubyte _displayedOpacity; GLubyte _realOpacity; Color3B _displayedColor; Color3B _realColor; bool _cascadeColorEnabled; bool _cascadeOpacityEnabled; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(NodeRGBA); }; // end of base_node group diff --git a/cocos/2d/CCScene.h b/cocos/2d/CCScene.h index 19f5c5f1cc..5355541096 100644 --- a/cocos/2d/CCScene.h +++ b/cocos/2d/CCScene.h @@ -56,18 +56,9 @@ public: static Scene *createWithPhysics(); #endif - Scene(); - /** - * @js NA - * @lua NA - */ - virtual ~Scene(); - - bool init(); - + #ifdef CC_USE_PHYSICS public: - bool initWithPhysics(); inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; } @@ -77,14 +68,23 @@ public: virtual void update(float delta) override; protected: - virtual void addChildToPhysicsWorld(Node* child); - -protected: + bool initWithPhysics(); + void addChildToPhysicsWorld(Node* child); + PhysicsWorld* _physicsWorld; #endif // CC_USE_PHYSICS - + + +protected: + Scene(); + virtual ~Scene(); + bool init(); + friend class Node; friend class SpriteBatchNode; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Scene); }; // end of scene group diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 186f569676..60f86ff429 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -70,10 +70,10 @@ Sprite* Sprite::createWithTexture(Texture2D *texture) return NULL; } -Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect) +Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated) { Sprite *sprite = new Sprite(); - if (sprite && sprite->initWithTexture(texture, rect)) + if (sprite && sprite->initWithTexture(texture, rect, rotated)) { sprite->autorelease(); return sprite; @@ -304,12 +304,18 @@ Sprite::~Sprite(void) CC_SAFE_RELEASE(_texture); } + +void Sprite::setTexture(const std::string &filename) +{ + Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); + setTexture(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; @@ -982,7 +988,17 @@ void Sprite::updateDisplayedOpacity(GLubyte opacity) // Frames -void Sprite::setDisplayFrame(SpriteFrame *pNewFrame) +void Sprite::setSpriteFrame(const std::string &spriteFrameName) +{ + SpriteFrameCache *cache = SpriteFrameCache::getInstance(); + SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName); + + CCASSERT(spriteFrame, "Invalid spriteFrameName"); + + setSpriteFrame(spriteFrame); +} + +void Sprite::setSpriteFrame(SpriteFrame *pNewFrame) { _unflippedOffsetPositionFromCenter = pNewFrame->getOffset(); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 317effad84..a0c70d4705 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -133,9 +133,10 @@ public: * @param texture A pointer to an existing Texture2D object. * You can use a Texture2D object for many sprites. * @param rect Only the contents inside the rect of this texture will be applied for this sprite. + * @param rotated Whether or not the rect is rotated * @return A valid sprite object that is marked as autoreleased. */ - static Sprite* createWithTexture(Texture2D *texture, const Rect& rect); + static Sprite* createWithTexture(Texture2D *texture, const Rect& rect, bool rotated=false); /** * Creates a sprite with an sprite frame. @@ -159,113 +160,6 @@ public: /// @} end of creators group - /// @{ - /// @name Initializers - - /** - * Default constructor - * @js ctor - */ - Sprite(void); - - /** - * Default destructor - * @js NA - * @lua NA - */ - virtual ~Sprite(void); - - /** - * Initializes an empty sprite with nothing init. - */ - virtual bool init(void); - - /** - * Initializes a sprite with a texture. - * - * After initialization, the rect used will be the size of the texture, and the offset will be (0,0). - * - * @param texture A pointer to an existing Texture2D object. - * You can use a Texture2D object for many sprites. - * @return true if the sprite is initialized properly, false otherwise. - */ - virtual bool initWithTexture(Texture2D *texture); - - /** - * Initializes a sprite with a texture and a rect. - * - * After initialization, the offset will be (0,0). - * - * @param texture A pointer to an exisiting Texture2D object. - * You can use a Texture2D object for many sprites. - * @param rect Only the contents inside rect of this texture will be applied for this sprite. - * @return true if the sprite is initialized properly, false otherwise. - */ - virtual bool initWithTexture(Texture2D *texture, const Rect& rect); - - /** - * Initializes a sprite with a texture and a rect in points, optionally rotated. - * - * After initialization, the offset will be (0,0). - * @note This is the designated initializer. - * - * @param texture A Texture2D object whose texture will be applied to this sprite. - * @param rect A rectangle assigned the contents of texture. - * @param rotated Whether or not the texture rectangle is rotated. - * @return true if the sprite is initialized properly, false otherwise. - */ - virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated); - - /** - * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite - * - * @param pSpriteFrame A SpriteFrame object. It should includes a valid texture and a rect - * @return true if the sprite is initialized properly, false otherwise. - */ - virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); - - /** - * Initializes a sprite with an sprite frame name. - * - * A SpriteFrame will be fetched from the SpriteFrameCache by name. - * If the SpriteFrame doesn't exist it will raise an exception. - * - * @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache - * @return true if the sprite is initialized properly, false otherwise. - */ - virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); - - /** - * Initializes a sprite with an image filename. - * - * This method will find filename from local file system, load its content to Texture2D, - * then use Texture2D to create a sprite. - * After initialization, the rect used will be the size of the image. The offset will be (0,0). - * - * @param filename The path to an image file in local file system - * @return true if the sprite is initialized properly, false otherwise. - * @js init - * @lua init - */ - virtual bool initWithFile(const std::string& filename); - - /** - * Initializes a sprite with an image filename, and a rect. - * - * This method will find filename from local file system, load its content to Texture2D, - * then use Texture2D to create a sprite. - * After initialization, the offset will be (0,0). - * - * @param filename The path to an image file in local file system. - * @param rect The rectangle assigned the content area from texture. - * @return true if the sprite is initialized properly, false otherwise. - * @js init - * @lua init - */ - virtual bool initWithFile(const std::string& filename, const Rect& rect); - - /// @} end of initializers - /// @{ /// @name BatchNode methods @@ -298,7 +192,10 @@ public: /// @{ - /// @name Texture methods + /// @name Texture / Frame methods + + /** Sets a new texture (from a filename) to the sprite */ + virtual void setTexture(const std::string &filename ); /** * Updates the texture rect of the Sprite in points. @@ -320,17 +217,14 @@ public: */ virtual void setVertexRect(const Rect& rect); - /// @} end of texture methods - - - - /// @{ - /// @name Frames methods - /** - * Sets a new display frame to the Sprite. + * Sets a new SpriteFrame to the Sprite. */ - virtual void setDisplayFrame(SpriteFrame *pNewFrame); + virtual void setSpriteFrame(SpriteFrame* newFrame); + virtual void setSpriteFrame(const std::string &spriteFrameName); + + /** @deprecated Use `setSpriteFrame()` instead. */ + virtual void setDisplayFrame(SpriteFrame *newFrame) CC_DEPRECATED_ATTRIBUTE { setSpriteFrame(newFrame); } /** * Returns whether or not a SpriteFrame is being displayed @@ -531,6 +425,97 @@ public: /// @} protected: + + Sprite(void); + virtual ~Sprite(void); + + /* Initializes an empty sprite with nothing init. */ + virtual bool init(void); + + /** + * Initializes a sprite with a texture. + * + * After initialization, the rect used will be the size of the texture, and the offset will be (0,0). + * + * @param texture A pointer to an existing Texture2D object. + * You can use a Texture2D object for many sprites. + * @return true if the sprite is initialized properly, false otherwise. + */ + virtual bool initWithTexture(Texture2D *texture); + + /** + * Initializes a sprite with a texture and a rect. + * + * After initialization, the offset will be (0,0). + * + * @param texture A pointer to an exisiting Texture2D object. + * You can use a Texture2D object for many sprites. + * @param rect Only the contents inside rect of this texture will be applied for this sprite. + * @return true if the sprite is initialized properly, false otherwise. + */ + virtual bool initWithTexture(Texture2D *texture, const Rect& rect); + + /** + * Initializes a sprite with a texture and a rect in points, optionally rotated. + * + * After initialization, the offset will be (0,0). + * @note This is the designated initializer. + * + * @param texture A Texture2D object whose texture will be applied to this sprite. + * @param rect A rectangle assigned the contents of texture. + * @param rotated Whether or not the texture rectangle is rotated. + * @return true if the sprite is initialized properly, false otherwise. + */ + virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated); + + /** + * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite + * + * @param pSpriteFrame A SpriteFrame object. It should includes a valid texture and a rect + * @return true if the sprite is initialized properly, false otherwise. + */ + virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame); + + /** + * Initializes a sprite with an sprite frame name. + * + * A SpriteFrame will be fetched from the SpriteFrameCache by name. + * If the SpriteFrame doesn't exist it will raise an exception. + * + * @param spriteFrameName A key string that can fected a volid SpriteFrame from SpriteFrameCache + * @return true if the sprite is initialized properly, false otherwise. + */ + virtual bool initWithSpriteFrameName(const std::string& spriteFrameName); + + /** + * Initializes a sprite with an image filename. + * + * This method will find filename from local file system, load its content to Texture2D, + * then use Texture2D to create a sprite. + * After initialization, the rect used will be the size of the image. The offset will be (0,0). + * + * @param filename The path to an image file in local file system + * @return true if the sprite is initialized properly, false otherwise. + * @js init + * @lua init + */ + virtual bool initWithFile(const std::string& filename); + + /** + * Initializes a sprite with an image filename, and a rect. + * + * This method will find filename from local file system, load its content to Texture2D, + * then use Texture2D to create a sprite. + * After initialization, the offset will be (0,0). + * + * @param filename The path to an image file in local file system. + * @param rect The rectangle assigned the content area from texture. + * @return true if the sprite is initialized properly, false otherwise. + * @js init + * @lua init + */ + virtual bool initWithFile(const std::string& filename, const Rect& rect); + void updateColor(void); virtual void setTextureCoords(Rect rect); virtual void updateBlendFunc(void); @@ -575,8 +560,11 @@ protected: bool _opacityModifyRGB; // image is flipped - bool _flippedX; /// Whether the sprite is flipped horizontally or not - bool _flippedY; /// Whether the sprite is flipped vertically or not + bool _flippedX; /// Whether the sprite is flipped horizontally or not + bool _flippedY; /// Whether the sprite is flipped vertically or not + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Sprite); }; diff --git a/cocos/2d/CCTMXLayer.cpp b/cocos/2d/CCTMXLayer.cpp index aa48b8b2b4..87a9893126 100644 --- a/cocos/2d/CCTMXLayer.cpp +++ b/cocos/2d/CCTMXLayer.cpp @@ -294,9 +294,9 @@ Sprite* TMXLayer::reusedTileWithRect(Rect rect) { if (! _reusedTile) { - _reusedTile = new Sprite(); - _reusedTile->initWithTexture(_textureAtlas->getTexture(), rect, false); + _reusedTile = Sprite::createWithTexture(_textureAtlas->getTexture(), rect); _reusedTile->setBatchNode(this); + _reusedTile->retain(); } else { @@ -335,8 +335,7 @@ Sprite * TMXLayer::getTileAt(const Point& pos) Rect rect = _tileSet->rectForGID(gid); rect = CC_RECT_PIXELS_TO_POINTS(rect); - tile = new Sprite(); - tile->initWithTexture(this->getTexture(), rect); + tile = Sprite::createWithTexture(this->getTexture(), rect); tile->setBatchNode(this); tile->setPosition(getPositionAt(pos)); tile->setVertexZ((float)getVertexZForPos(pos)); @@ -345,7 +344,6 @@ Sprite * TMXLayer::getTileAt(const Point& pos) unsigned int indexForZ = atlasIndexForExistantZ(z); this->addSpriteWithoutQuad(tile, indexForZ, z); - tile->release(); } } diff --git a/cocos/2d/CCTransition.cpp b/cocos/2d/CCTransition.cpp index 4642b7404b..4477c9a41a 100644 --- a/cocos/2d/CCTransition.cpp +++ b/cocos/2d/CCTransition.cpp @@ -77,7 +77,6 @@ bool TransitionScene::initWithDuration(float t, Scene *scene) if (_outScene == NULL) { _outScene = Scene::create(); - _outScene->init(); } _outScene->retain(); diff --git a/cocos/2d/ccMacros.h b/cocos/2d/ccMacros.h index dbea2d512a..f82f3c9284 100644 --- a/cocos/2d/ccMacros.h +++ b/cocos/2d/ccMacros.h @@ -257,4 +257,22 @@ extern unsigned int CC_DLL g_uNumberOfDraws; */ #define AnimationFrameDisplayedNotification "CCAnimationFrameDisplayedNotification" +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class +#define CC_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + void operator=(const TypeName&) + +// A macro to disallow all the implicit constructors, namely the +// default constructor, copy constructor and operator= functions. +// +// This should be used in the private: declarations for a class +// that wants to prevent anyone from instantiating it. This is +// especially useful for classes containing only static methods. +#define CC_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName(); \ + CC_DISALLOW_COPY_AND_ASSIGN(TypeName) + + + #endif // __CCMACROS_H__ diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index d18627be1e..a8ccb322ee 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -193,10 +193,10 @@ void UIButton::loadTextureNormal(const char* normal,TextureResType texType) switch (_normalTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonNormalRenderer)->initWithFile(normal); + dynamic_cast(_buttonNormalRenderer)->setTexture(normal); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonNormalRenderer)->initWithSpriteFrameName(normal); + dynamic_cast(_buttonNormalRenderer)->setSpriteFrame(normal); break; default: break; @@ -239,10 +239,10 @@ void UIButton::loadTexturePressed(const char* selected,TextureResType texType) switch (_pressedTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonClickedRenderer)->initWithFile(selected); + dynamic_cast(_buttonClickedRenderer)->setTexture(selected); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonClickedRenderer)->initWithSpriteFrameName(selected); + dynamic_cast(_buttonClickedRenderer)->setSpriteFrame(selected); break; default: break; @@ -285,10 +285,10 @@ void UIButton::loadTextureDisabled(const char* disabled,TextureResType texType) switch (_disabledTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_buttonDisableRenderer)->initWithFile(disabled); + dynamic_cast(_buttonDisableRenderer)->setTexture(disabled); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_buttonDisableRenderer)->initWithSpriteFrameName(disabled); + dynamic_cast(_buttonDisableRenderer)->setSpriteFrame(disabled); break; default: break; diff --git a/cocos/gui/UICheckBox.cpp b/cocos/gui/UICheckBox.cpp index 511d03a7ea..21d5be4f0a 100644 --- a/cocos/gui/UICheckBox.cpp +++ b/cocos/gui/UICheckBox.cpp @@ -112,10 +112,10 @@ void UICheckBox::loadTextureBackGround(const char *backGround,TextureResType tex switch (_backGroundTexType) { case UI_TEX_TYPE_LOCAL: - _backGroundBoxRenderer->initWithFile(backGround); + _backGroundBoxRenderer->setTexture(backGround); break; case UI_TEX_TYPE_PLIST: - _backGroundBoxRenderer->initWithSpriteFrameName(backGround); + _backGroundBoxRenderer->setSpriteFrame(backGround); break; default: break; @@ -136,10 +136,10 @@ void UICheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,Te switch (_backGroundSelectedTexType) { case UI_TEX_TYPE_LOCAL: - _backGroundSelectedBoxRenderer->initWithFile(backGroundSelected); + _backGroundSelectedBoxRenderer->setTexture(backGroundSelected); break; case UI_TEX_TYPE_PLIST: - _backGroundSelectedBoxRenderer->initWithSpriteFrameName(backGroundSelected); + _backGroundSelectedBoxRenderer->setSpriteFrame(backGroundSelected); break; default: break; @@ -160,10 +160,10 @@ void UICheckBox::loadTextureFrontCross(const char *cross,TextureResType texType) switch (_frontCrossTexType) { case UI_TEX_TYPE_LOCAL: - _frontCrossRenderer->initWithFile(cross); + _frontCrossRenderer->setTexture(cross); break; case UI_TEX_TYPE_PLIST: - _frontCrossRenderer->initWithSpriteFrameName(cross); + _frontCrossRenderer->setSpriteFrame(cross); break; default: break; @@ -184,10 +184,10 @@ void UICheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,Te switch (_backGroundDisabledTexType) { case UI_TEX_TYPE_LOCAL: - _backGroundBoxDisabledRenderer->initWithFile(backGroundDisabled); + _backGroundBoxDisabledRenderer->setTexture(backGroundDisabled); break; case UI_TEX_TYPE_PLIST: - _backGroundBoxDisabledRenderer->initWithSpriteFrameName(backGroundDisabled); + _backGroundBoxDisabledRenderer->setSpriteFrame(backGroundDisabled); break; default: break; @@ -208,10 +208,10 @@ void UICheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Te switch (_frontCrossDisabledTexType) { case UI_TEX_TYPE_LOCAL: - _frontCrossDisabledRenderer->initWithFile(frontCrossDisabled); + _frontCrossDisabledRenderer->setTexture(frontCrossDisabled); break; case UI_TEX_TYPE_PLIST: - _frontCrossDisabledRenderer->initWithSpriteFrameName(frontCrossDisabled); + _frontCrossDisabledRenderer->setSpriteFrame(frontCrossDisabled); break; default: break; diff --git a/cocos/gui/UIImageView.cpp b/cocos/gui/UIImageView.cpp index 68d604f21a..6316663231 100644 --- a/cocos/gui/UIImageView.cpp +++ b/cocos/gui/UIImageView.cpp @@ -92,7 +92,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) } else { - DYNAMIC_CAST_CCSPRITE->initWithFile(fileName); + DYNAMIC_CAST_CCSPRITE->setTexture(fileName); DYNAMIC_CAST_CCSPRITE->setColor(getColor()); DYNAMIC_CAST_CCSPRITE->setOpacity(getOpacity()); } @@ -107,7 +107,7 @@ void UIImageView::loadTexture(const char *fileName, TextureResType texType) } else { - DYNAMIC_CAST_CCSPRITE->initWithSpriteFrameName(fileName); + DYNAMIC_CAST_CCSPRITE->setSpriteFrame(fileName); DYNAMIC_CAST_CCSPRITE->setColor(getColor()); DYNAMIC_CAST_CCSPRITE->setOpacity(getOpacity()); } diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 9a25d57b13..756f25b9ca 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -214,10 +214,10 @@ void UILayout::setBackGroundImage(const char* fileName,TextureResType texType) switch (_bgImageTexType) { case UI_TEX_TYPE_LOCAL: - dynamic_cast(_backGroundImage)->initWithFile(fileName); + dynamic_cast(_backGroundImage)->setTexture(fileName); break; case UI_TEX_TYPE_PLIST: - dynamic_cast(_backGroundImage)->initWithSpriteFrameName(fileName); + dynamic_cast(_backGroundImage)->setSpriteFrame(fileName); break; default: break; diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index 09b78c7b25..11362d61bb 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -121,7 +121,7 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) } else { - dynamic_cast(_barRenderer)->initWithFile(texture); + dynamic_cast(_barRenderer)->setTexture(texture); } break; case UI_TEX_TYPE_PLIST: @@ -132,7 +132,7 @@ void UILoadingBar::loadTexture(const char* texture,TextureResType texType) } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(texture); + dynamic_cast(_barRenderer)->setSpriteFrame(texture); } break; default: diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index d8f2f95e86..51333f1cee 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -111,7 +111,7 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) } else { - dynamic_cast(_barRenderer)->initWithFile(fileName); + dynamic_cast(_barRenderer)->setTexture(fileName); } break; case UI_TEX_TYPE_PLIST: @@ -121,7 +121,7 @@ void UISlider::loadBarTexture(const char* fileName, TextureResType texType) } else { - dynamic_cast(_barRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_barRenderer)->setSpriteFrame(fileName); } break; default: @@ -157,7 +157,7 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy } else { - dynamic_cast(_progressBarRenderer)->initWithFile(fileName); + dynamic_cast(_progressBarRenderer)->setTexture(fileName); } break; case UI_TEX_TYPE_PLIST: @@ -167,7 +167,7 @@ void UISlider::loadProgressBarTexture(const char *fileName, TextureResType texTy } else { - dynamic_cast(_progressBarRenderer)->initWithSpriteFrameName(fileName); + dynamic_cast(_progressBarRenderer)->setSpriteFrame(fileName); } break; default: @@ -281,10 +281,10 @@ void UISlider::loadSlidBallTextureNormal(const char* normal,TextureResType texTy switch (_ballNTexType) { case UI_TEX_TYPE_LOCAL: - _slidBallNormalRenderer->initWithFile(normal); + _slidBallNormalRenderer->setTexture(normal); break; case UI_TEX_TYPE_PLIST: - _slidBallNormalRenderer->initWithSpriteFrameName(normal); + _slidBallNormalRenderer->setSpriteFrame(normal); break; default: break; @@ -304,10 +304,10 @@ void UISlider::loadSlidBallTexturePressed(const char* pressed,TextureResType tex switch (_ballPTexType) { case UI_TEX_TYPE_LOCAL: - _slidBallPressedRenderer->initWithFile(pressed); + _slidBallPressedRenderer->setTexture(pressed); break; case UI_TEX_TYPE_PLIST: - _slidBallPressedRenderer->initWithSpriteFrameName(pressed); + _slidBallPressedRenderer->setSpriteFrame(pressed); break; default: break; @@ -327,10 +327,10 @@ void UISlider::loadSlidBallTextureDisabled(const char* disabled,TextureResType t switch (_ballDTexType) { case UI_TEX_TYPE_LOCAL: - _slidBallDisabledRenderer->initWithFile(disabled); + _slidBallDisabledRenderer->setTexture(disabled); break; case UI_TEX_TYPE_PLIST: - _slidBallDisabledRenderer->initWithSpriteFrameName(disabled); + _slidBallDisabledRenderer->setSpriteFrame(disabled); break; default: break; diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 599bcb5f36..8ad857fd7c 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -245,48 +245,49 @@ bool Scale9Sprite::updateWithBatchNode(SpriteBatchNode* batchnode, const Rect& o centertopbounds = RectApplyAffineTransform(centertopbounds, t); // Centre - _centre = new Sprite(); - _centre->initWithTexture(_scale9Image->getTexture(), centerbounds); + _centre = Sprite::createWithTexture(_scale9Image->getTexture(), centerbounds); + _centre->retain(); _scale9Image->addChild(_centre, 0, pCentre); + // Top - _top = new Sprite(); - _top->initWithTexture(_scale9Image->getTexture(), centertopbounds); + _top = Sprite::createWithTexture(_scale9Image->getTexture(), centertopbounds); + _top->retain(); _scale9Image->addChild(_top, 1, pTop); // Bottom - _bottom = new Sprite(); - _bottom->initWithTexture(_scale9Image->getTexture(), centerbottombounds); + _bottom = Sprite::createWithTexture(_scale9Image->getTexture(), centerbottombounds); + _bottom->retain(); _scale9Image->addChild(_bottom, 1, pBottom); // Left - _left = new Sprite(); - _left->initWithTexture(_scale9Image->getTexture(), leftcenterbounds); + _left = Sprite::createWithTexture(_scale9Image->getTexture(), leftcenterbounds); + _left->retain(); _scale9Image->addChild(_left, 1, pLeft); // Right - _right = new Sprite(); - _right->initWithTexture(_scale9Image->getTexture(), rightcenterbounds); + _right = Sprite::createWithTexture(_scale9Image->getTexture(), rightcenterbounds); + _right->retain(); _scale9Image->addChild(_right, 1, pRight); // Top left - _topLeft = new Sprite(); - _topLeft->initWithTexture(_scale9Image->getTexture(), lefttopbounds); + _topLeft = Sprite::createWithTexture(_scale9Image->getTexture(), lefttopbounds); + _topLeft->retain(); _scale9Image->addChild(_topLeft, 2, pTopLeft); // Top right - _topRight = new Sprite(); - _topRight->initWithTexture(_scale9Image->getTexture(), righttopbounds); + _topRight = Sprite::createWithTexture(_scale9Image->getTexture(), righttopbounds); + _topRight->retain(); _scale9Image->addChild(_topRight, 2, pTopRight); // Bottom left - _bottomLeft = new Sprite(); - _bottomLeft->initWithTexture(_scale9Image->getTexture(), leftbottombounds); + _bottomLeft = Sprite::createWithTexture(_scale9Image->getTexture(), leftbottombounds); + _bottomLeft->retain(); _scale9Image->addChild(_bottomLeft, 2, pBottomLeft); // Bottom right - _bottomRight = new Sprite(); - _bottomRight->initWithTexture(_scale9Image->getTexture(), rightbottombounds); + _bottomRight = Sprite::createWithTexture(_scale9Image->getTexture(), rightbottombounds); + _bottomRight->retain(); _scale9Image->addChild(_bottomRight, 2, pBottomRight); } else { // set up transformation of coordinates @@ -330,48 +331,48 @@ bool Scale9Sprite::updateWithBatchNode(SpriteBatchNode* batchnode, const Rect& o rotatedcentertopbounds.origin = centertopbounds.origin; // Centre - _centre = new Sprite(); - _centre->initWithTexture(_scale9Image->getTexture(), rotatedcenterbounds, true); + _centre = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedcenterbounds, true); + _centre->retain(); _scale9Image->addChild(_centre, 0, pCentre); // Top - _top = new Sprite(); - _top->initWithTexture(_scale9Image->getTexture(), rotatedcentertopbounds, true); + _top = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedcentertopbounds, true); + _top->retain(); _scale9Image->addChild(_top, 1, pTop); // Bottom - _bottom = new Sprite(); - _bottom->initWithTexture(_scale9Image->getTexture(), rotatedcenterbottombounds, true); + _bottom = Sprite::Sprite::createWithTexture(_scale9Image->getTexture(), rotatedcenterbottombounds, true); + _bottom->retain(); _scale9Image->addChild(_bottom, 1, pBottom); // Left - _left = new Sprite(); - _left->initWithTexture(_scale9Image->getTexture(), rotatedleftcenterbounds, true); + _left = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedleftcenterbounds, true); + _left->retain(); _scale9Image->addChild(_left, 1, pLeft); // Right - _right = new Sprite(); - _right->initWithTexture(_scale9Image->getTexture(), rotatedrightcenterbounds, true); + _right = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedrightcenterbounds, true); + _right->retain(); _scale9Image->addChild(_right, 1, pRight); // Top left - _topLeft = new Sprite(); - _topLeft->initWithTexture(_scale9Image->getTexture(), rotatedlefttopbounds, true); + _topLeft = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedlefttopbounds, true); + _topLeft->retain(); _scale9Image->addChild(_topLeft, 2, pTopLeft); // Top right - _topRight = new Sprite(); - _topRight->initWithTexture(_scale9Image->getTexture(), rotatedrighttopbounds, true); + _topRight = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedrighttopbounds, true); + _topRight->retain(); _scale9Image->addChild(_topRight, 2, pTopRight); // Bottom left - _bottomLeft = new Sprite(); - _bottomLeft->initWithTexture(_scale9Image->getTexture(), rotatedleftbottombounds, true); + _bottomLeft = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedleftbottombounds, true); + _bottomLeft->retain(); _scale9Image->addChild(_bottomLeft, 2, pBottomLeft); // Bottom right - _bottomRight = new Sprite(); - _bottomRight->initWithTexture(_scale9Image->getTexture(), rotatedrightbottombounds, true); + _bottomRight = Sprite::createWithTexture(_scale9Image->getTexture(), rotatedrightbottombounds, true); + _bottomRight->retain(); _scale9Image->addChild(_bottomRight, 2, pBottomRight); } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 703e8bf40b..66e8e6edb1 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -63,9 +63,6 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -77,18 +74,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h index f67907ceba..9a601b5212 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h @@ -40,6 +40,8 @@ public: class ActionManual : public ActionsDemo { public: + CREATE_FUNC(ActionManual); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -47,6 +49,8 @@ public: class ActionMove : public ActionsDemo { public: + CREATE_FUNC(ActionMove); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -54,6 +58,8 @@ public: class ActionScale : public ActionsDemo { public: + CREATE_FUNC(ActionScale); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -61,6 +67,8 @@ public: class ActionSkew : public ActionsDemo { public: + CREATE_FUNC(ActionSkew); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -68,6 +76,8 @@ public: class ActionRotationalSkew : public ActionsDemo { public: + CREATE_FUNC(ActionRotationalSkew); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -75,6 +85,8 @@ public: class ActionRotationalSkewVSStandardSkew : public ActionsDemo { public: + CREATE_FUNC(ActionRotationalSkewVSStandardSkew); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -82,6 +94,8 @@ public: class ActionSkewRotateScale : public ActionsDemo { public: + CREATE_FUNC(ActionSkewRotateScale); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -89,6 +103,8 @@ public: class ActionRotate : public ActionsDemo { public: + CREATE_FUNC(ActionRotate); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -96,6 +112,8 @@ public: class ActionJump : public ActionsDemo { public: + CREATE_FUNC(ActionJump); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -103,6 +121,8 @@ public: class ActionBezier : public ActionsDemo { public: + CREATE_FUNC(ActionBezier); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -110,6 +130,8 @@ public: class ActionBlink : public ActionsDemo { public: + CREATE_FUNC(ActionBlink); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -117,6 +139,8 @@ public: class ActionFade : public ActionsDemo { public: + CREATE_FUNC(ActionFade); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -124,6 +148,8 @@ public: class ActionTint : public ActionsDemo { public: + CREATE_FUNC(ActionTint); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -131,6 +157,8 @@ public: class ActionAnimate : public ActionsDemo { public: + CREATE_FUNC(ActionAnimate); + virtual void onEnter(); virtual void onExit(); virtual std::string title(); @@ -140,6 +168,8 @@ public: class ActionSequence : public ActionsDemo { public: + CREATE_FUNC(ActionSequence); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -147,6 +177,8 @@ public: class ActionSequence2 : public ActionsDemo { public: + CREATE_FUNC(ActionSequence2); + virtual void onEnter(); virtual std::string subtitle(); @@ -158,6 +190,8 @@ public: class ActionSpawn : public ActionsDemo { public: + CREATE_FUNC(ActionSpawn); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -165,6 +199,8 @@ public: class ActionReverse : public ActionsDemo { public: + CREATE_FUNC(ActionReverse); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -172,6 +208,8 @@ public: class ActionRepeat : public ActionsDemo { public: + CREATE_FUNC(ActionRepeat); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -179,6 +217,8 @@ public: class ActionDelayTime : public ActionsDemo { public: + CREATE_FUNC(ActionDelayTime); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -186,6 +226,8 @@ public: class ActionReverseSequence : public ActionsDemo { public: + CREATE_FUNC(ActionReverseSequence); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -193,6 +235,8 @@ public: class ActionReverseSequence2 : public ActionsDemo { public: + CREATE_FUNC(ActionReverseSequence2); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -200,6 +244,8 @@ public: class ActionOrbit : public ActionsDemo { public: + CREATE_FUNC(ActionOrbit); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -207,6 +253,8 @@ public: class ActionRemoveSelf : public ActionsDemo { public: + CREATE_FUNC(ActionRemoveSelf); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -214,6 +262,8 @@ public: class ActionRepeatForever : public ActionsDemo { public: + CREATE_FUNC(ActionRepeatForever); + virtual void onEnter(); virtual std::string subtitle(); @@ -223,6 +273,8 @@ public: class ActionRotateToRepeat : public ActionsDemo { public: + CREATE_FUNC(ActionRotateToRepeat); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -230,6 +282,8 @@ public: class ActionRotateJerk : public ActionsDemo { public: + CREATE_FUNC(ActionRotateJerk); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -237,6 +291,8 @@ public: class ActionCallFuncN : public ActionsDemo { public: + CREATE_FUNC(ActionCallFuncN); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -246,6 +302,8 @@ public: class ActionCallFuncND : public ActionsDemo { public: + CREATE_FUNC(ActionCallFuncND); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -255,6 +313,8 @@ public: class ActionCallFuncO : public ActionsDemo { public: + CREATE_FUNC(ActionCallFuncO); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -264,6 +324,8 @@ public: class ActionCallFunction : public ActionsDemo { public: + CREATE_FUNC(ActionCallFunction); + virtual void onEnter(); virtual std::string subtitle(); @@ -276,6 +338,8 @@ public: class ActionFollow : public ActionsDemo { public: + CREATE_FUNC(ActionFollow); + virtual void onEnter(); virtual void draw(); virtual std::string subtitle(); @@ -284,6 +348,8 @@ public: class ActionTargeted : public ActionsDemo { public: + CREATE_FUNC(ActionTargeted); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -292,6 +358,8 @@ public: class ActionTargetedReverse : public ActionsDemo { public: + CREATE_FUNC(ActionTargetedReverse); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -300,6 +368,8 @@ public: class ActionStacked : public ActionsDemo { public: + CREATE_FUNC(ActionStacked); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -311,6 +381,8 @@ public: class ActionMoveStacked : public ActionStacked { public: + CREATE_FUNC(ActionMoveStacked); + virtual std::string title(); virtual void runActionsInSprite(Sprite* sprite); }; @@ -318,6 +390,8 @@ public: class ActionMoveJumpStacked : public ActionStacked { public: + CREATE_FUNC(ActionMoveJumpStacked); + virtual std::string title(); virtual void runActionsInSprite(Sprite* sprite); }; @@ -325,6 +399,8 @@ public: class ActionMoveBezierStacked : public ActionStacked { public: + CREATE_FUNC(ActionMoveBezierStacked); + virtual std::string title(); virtual void runActionsInSprite(Sprite* sprite); }; @@ -332,6 +408,8 @@ public: class ActionCatmullRomStacked : public ActionsDemo { public: + CREATE_FUNC(ActionCatmullRomStacked); + virtual ~ActionCatmullRomStacked(); virtual void draw(); virtual void onEnter(); @@ -345,6 +423,8 @@ private: class ActionCardinalSplineStacked : public ActionsDemo { public: + CREATE_FUNC(ActionCardinalSplineStacked); + virtual ~ActionCardinalSplineStacked(); virtual void draw(); virtual void onEnter(); @@ -357,6 +437,8 @@ private: class Issue1305 : public ActionsDemo { public: + CREATE_FUNC(Issue1305); + virtual void onEnter(); virtual void onExit(); void log(Node* sender); @@ -370,6 +452,8 @@ private: class Issue1305_2 : public ActionsDemo { public: + CREATE_FUNC(Issue1305_2); + virtual void onEnter(); void printLog1(); void printLog2(); @@ -382,6 +466,8 @@ public: class Issue1288 : public ActionsDemo { public: + CREATE_FUNC(Issue1288); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -390,6 +476,8 @@ public: class Issue1288_2 : public ActionsDemo { public: + CREATE_FUNC(Issue1288_2); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -398,6 +486,8 @@ public: class Issue1327 : public ActionsDemo { public: + CREATE_FUNC(Issue1327); + virtual void onEnter(); virtual std::string subtitle(); virtual std::string title(); @@ -407,6 +497,8 @@ public: class Issue1398 : public ActionsDemo { public: + CREATE_FUNC(Issue1398); + void incrementInteger(); void incrementIntegerCallback(void* data); virtual void onEnter(); @@ -419,6 +511,8 @@ private: class ActionCatmullRom : public ActionsDemo { public: + CREATE_FUNC(ActionCatmullRom); + ~ActionCatmullRom(); virtual void onEnter(); @@ -433,6 +527,8 @@ private: class ActionCardinalSpline : public ActionsDemo { public: + CREATE_FUNC(ActionCardinalSpline); + ~ActionCardinalSpline(); virtual void onEnter(); @@ -446,6 +542,8 @@ private: class PauseResumeActions : public ActionsDemo { public: + CREATE_FUNC(PauseResumeActions); + PauseResumeActions(); virtual ~PauseResumeActions(); virtual void onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index f69ba49240..bec4eddd83 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -57,9 +57,6 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -71,18 +68,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h index 042e51ddf6..4cf5d1bb0d 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h @@ -7,6 +7,8 @@ class BaseClippingNodeTest : public BaseTest { public: + CREATE_FUNC(BaseClippingNodeTest); + ~BaseClippingNodeTest(); virtual bool init(); @@ -22,6 +24,8 @@ public: class BasicTest : public BaseClippingNodeTest { public: + CREATE_FUNC(BasicTest); + virtual std::string title(); virtual std::string subtitle(); virtual void setup(); @@ -40,6 +44,8 @@ public: class ShapeTest : public BasicTest { public: + CREATE_FUNC(ShapeTest); + virtual std::string title(); virtual std::string subtitle(); @@ -50,6 +56,8 @@ public: class ShapeInvertedTest : public ShapeTest { public: + CREATE_FUNC(ShapeInvertedTest); + virtual std::string title(); virtual std::string subtitle(); virtual ClippingNode* clipper(); @@ -58,6 +66,8 @@ public: class SpriteTest : public BasicTest { public: + CREATE_FUNC(SpriteTest); + virtual std::string title(); virtual std::string subtitle(); @@ -69,6 +79,8 @@ public: class SpriteNoAlphaTest : public SpriteTest { public: + CREATE_FUNC(SpriteNoAlphaTest); + virtual std::string title(); virtual std::string subtitle(); virtual ClippingNode* clipper(); @@ -77,6 +89,8 @@ public: class SpriteInvertedTest : public SpriteTest { public: + CREATE_FUNC(SpriteInvertedTest); + virtual std::string title(); virtual std::string subtitle(); virtual ClippingNode* clipper(); @@ -85,6 +99,8 @@ public: class NestedTest : public BaseClippingNodeTest { public: + CREATE_FUNC(NestedTest); + virtual std::string title(); virtual std::string subtitle(); virtual void setup(); @@ -93,6 +109,8 @@ public: class HoleDemo : public BaseClippingNodeTest { public: + CREATE_FUNC(HoleDemo); + ~HoleDemo(); virtual void setup(); virtual std::string title(); @@ -108,6 +126,8 @@ private: class ScrollViewDemo : public BaseClippingNodeTest { public: + CREATE_FUNC(ScrollViewDemo); + virtual std::string title(); virtual std::string subtitle(); virtual void setup(); @@ -124,6 +144,8 @@ private: class RawStencilBufferTest : public BaseClippingNodeTest { public: + CREATE_FUNC(RawStencilBufferTest); + ~RawStencilBufferTest(); virtual std::string title(); @@ -141,6 +163,8 @@ protected: class RawStencilBufferTest2 : public RawStencilBufferTest { public: + CREATE_FUNC(RawStencilBufferTest2); + virtual std::string subtitle(); virtual void setupStencilForClippingOnPlane(GLint plane); virtual void setupStencilForDrawingOnPlane(GLint plane); @@ -149,6 +173,8 @@ public: class RawStencilBufferTest3 : public RawStencilBufferTest { public: + CREATE_FUNC(RawStencilBufferTest3); + virtual std::string subtitle(); virtual void setupStencilForClippingOnPlane(GLint plane); virtual void setupStencilForDrawingOnPlane(GLint plane); @@ -157,6 +183,8 @@ public: class RawStencilBufferTest4 : public RawStencilBufferTest { public: + CREATE_FUNC(RawStencilBufferTest4); + virtual std::string subtitle(); virtual void setupStencilForClippingOnPlane(GLint plane); virtual void setupStencilForDrawingOnPlane(GLint plane); @@ -165,6 +193,8 @@ public: class RawStencilBufferTest5 : public RawStencilBufferTest { public: + CREATE_FUNC(RawStencilBufferTest5); + virtual std::string subtitle(); virtual void setupStencilForClippingOnPlane(GLint plane); virtual void setupStencilForDrawingOnPlane(GLint plane); @@ -173,6 +203,8 @@ public: class RawStencilBufferTest6 : public RawStencilBufferTest { public: + CREATE_FUNC(RawStencilBufferTest6); + virtual std::string subtitle(); virtual void setup(); virtual void setupStencilForClippingOnPlane(GLint plane); @@ -184,6 +216,8 @@ public: class ClippingNodeTestScene : public TestScene { public: + CREATE_FUNC(ClippingNodeTestScene); + virtual void runThisTest(); }; diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp index 9ff65566a1..fa9b5b7a4c 100644 --- a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp @@ -26,9 +26,6 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -40,18 +37,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restartAction() { - auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - + auto layer = (createFunctions[sceneIdx])(); return layer; } diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h index 807719cea0..1075d19773 100644 --- a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h +++ b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h @@ -35,6 +35,8 @@ public: class ConfigurationLoadConfig : public ConfigurationBase { public: + CREATE_FUNC(ConfigurationLoadConfig); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -42,6 +44,8 @@ public: class ConfigurationQuery : public ConfigurationBase { public: + CREATE_FUNC(ConfigurationQuery); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -49,6 +53,8 @@ public: class ConfigurationInvalid : public ConfigurationBase { public: + CREATE_FUNC(ConfigurationInvalid); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -56,6 +62,8 @@ public: class ConfigurationDefault : public ConfigurationBase { public: + CREATE_FUNC(ConfigurationDefault); + virtual void onEnter(); virtual std::string subtitle(); }; @@ -63,6 +71,8 @@ public: class ConfigurationSet : public ConfigurationBase { public: + CREATE_FUNC(ConfigurationSet); + virtual void onEnter(); virtual std::string subtitle(); }; diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp index ee0bfe043b..ac05ac2e03 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp @@ -58,9 +58,6 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -72,18 +69,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h index 232d05419a..190d82c0ad 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h @@ -50,6 +50,8 @@ public: class S9BatchNodeBasic : public S9SpriteTestDemo { public: + CREATE_FUNC(S9BatchNodeBasic); + virtual void onEnter(); virtual std::string title(); @@ -61,6 +63,8 @@ public: class S9FrameNameSpriteSheet : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheet); + virtual void onEnter(); virtual std::string title(); @@ -72,6 +76,8 @@ public: class S9FrameNameSpriteSheetRotated : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetRotated); + virtual void onEnter(); virtual std::string title(); @@ -83,6 +89,8 @@ public: class S9BatchNodeScaledNoInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9BatchNodeScaledNoInsets); + virtual void onEnter(); virtual std::string title(); @@ -94,6 +102,8 @@ public: class S9FrameNameSpriteSheetScaledNoInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetScaledNoInsets); + virtual void onEnter(); virtual std::string title(); @@ -105,6 +115,8 @@ public: class S9FrameNameSpriteSheetRotatedScaledNoInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetRotatedScaledNoInsets); + virtual void onEnter(); virtual std::string title(); @@ -117,6 +129,8 @@ public: class S9BatchNodeScaleWithCapInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9BatchNodeScaleWithCapInsets); + virtual void onEnter(); virtual std::string title(); @@ -128,6 +142,8 @@ public: class S9FrameNameSpriteSheetInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetInsets); + virtual void onEnter(); virtual std::string title(); @@ -139,6 +155,8 @@ public: class S9FrameNameSpriteSheetInsetsScaled : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetInsetsScaled); + virtual void onEnter(); virtual std::string title(); @@ -150,6 +168,8 @@ public: class S9FrameNameSpriteSheetRotatedInsets : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetRotatedInsets); + virtual void onEnter(); virtual std::string title(); @@ -161,6 +181,8 @@ public: class S9_TexturePacker : public S9SpriteTestDemo { public: + CREATE_FUNC(S9_TexturePacker); + virtual void onEnter(); virtual std::string title(); @@ -172,6 +194,8 @@ public: class S9FrameNameSpriteSheetRotatedInsetsScaled : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetRotatedInsetsScaled); + virtual void onEnter(); virtual std::string title(); @@ -183,6 +207,8 @@ public: class S9FrameNameSpriteSheetRotatedSetCapInsetLater : public S9SpriteTestDemo { public: + CREATE_FUNC(S9FrameNameSpriteSheetRotatedSetCapInsetLater); + virtual void onEnter(); virtual std::string title(); @@ -194,6 +220,8 @@ public: class S9CascadeOpacityAndColor : public S9SpriteTestDemo { public: + CREATE_FUNC(S9CascadeOpacityAndColor); + virtual void onEnter(); virtual std::string title(); diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp index 4211828903..66d15719ce 100644 --- a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -24,9 +24,6 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -38,18 +35,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h index d524d81a4b..93d1a98df2 100644 --- a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h +++ b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h @@ -27,6 +27,8 @@ public: class TestResolutionDirectories : public FileUtilsDemo { public: + CREATE_FUNC(TestResolutionDirectories); + virtual void onEnter(); virtual void onExit(); virtual string title(); @@ -39,6 +41,8 @@ private: class TestSearchPath : public FileUtilsDemo { public: + CREATE_FUNC(TestSearchPath); + virtual void onEnter(); virtual void onExit(); virtual string title(); @@ -51,6 +55,8 @@ private: class TestFilenameLookup : public FileUtilsDemo { public: + CREATE_FUNC(TestFilenameLookup); + virtual void onEnter(); virtual void onExit(); virtual string title(); @@ -60,6 +66,8 @@ public: class TestIsFileExist : public FileUtilsDemo { public: + CREATE_FUNC(TestIsFileExist); + virtual void onEnter(); virtual void onExit(); virtual string title(); @@ -69,6 +77,8 @@ public: class TextWritePlist : public FileUtilsDemo { public: + CREATE_FUNC(TextWritePlist); + virtual void onEnter(); virtual void onExit(); virtual string title(); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 1828dbb03d..a9ff786e4a 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -227,6 +227,9 @@ std::string TouchableSpriteTest::subtitle() class TouchableSpriteWithFixedPriority : public Sprite { public: + + CREATE_FUNC(TouchableSpriteWithFixedPriority); + TouchableSpriteWithFixedPriority() : _listener(nullptr) , _fixedPriority(0) @@ -297,23 +300,20 @@ void FixedPriorityTest::onEnter() Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); - auto sprite1 = new TouchableSpriteWithFixedPriority(); - sprite1->initWithFile("Images/CyanSquare.png"); - sprite1->autorelease(); + auto sprite1 = TouchableSpriteWithFixedPriority::create(); + sprite1->setTexture("Images/CyanSquare.png"); sprite1->setPriority(30); sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 40)); addChild(sprite1, 10); - auto sprite2 = new TouchableSpriteWithFixedPriority(); - sprite2->initWithFile("Images/MagentaSquare.png"); - sprite2->autorelease(); + auto sprite2 = TouchableSpriteWithFixedPriority::create(); + sprite2->setTexture("Images/MagentaSquare.png"); sprite2->setPriority(20); sprite2->setPosition(origin+Point(size.width/2, size.height/2)); addChild(sprite2, 20); - auto sprite3 = new TouchableSpriteWithFixedPriority(); - sprite3->initWithFile("Images/YellowSquare.png"); - sprite3->autorelease(); + auto sprite3 = TouchableSpriteWithFixedPriority::create(); + sprite3->setTexture("Images/YellowSquare.png"); sprite3->setPriority(10); sprite3->setPosition(Point(0, 0)); sprite2->addChild(sprite3, 1); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp index 55da98b32d..af0ec78e7d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp @@ -292,8 +292,7 @@ void NodeDeallocTest::update(float dt) Node **nodes = new Node*[quantityOfNodes]; for( int i=0; iinit(); + nodes[i] = Node::create(); } CC_PROFILER_START(this->profilerName()); @@ -445,8 +444,8 @@ void SpriteDeallocTest::update(float dt) Sprite **sprites = new Sprite*[quantityOfNodes]; for( int i=0; iinit(); + sprites[i] = Sprite::create(); + sprites[i]->retain(); } CC_PROFILER_START(this->profilerName()); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h index fcfdba36ec..aa8e5d5fff 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h @@ -49,6 +49,8 @@ protected: class NodeCreateTest : public PerformceAllocScene { public: + CREATE_FUNC(NodeCreateTest); + virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void update(float dt); @@ -61,6 +63,8 @@ public: class NodeDeallocTest : public PerformceAllocScene { public: + CREATE_FUNC(NodeDeallocTest); + virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void update(float dt); @@ -73,6 +77,8 @@ public: class SpriteCreateEmptyTest : public PerformceAllocScene { public: + CREATE_FUNC(SpriteCreateEmptyTest); + virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void update(float dt); @@ -85,6 +91,8 @@ public: class SpriteCreateTest : public PerformceAllocScene { public: + CREATE_FUNC(SpriteCreateTest); + virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void update(float dt); @@ -97,6 +105,8 @@ public: class SpriteDeallocTest : public PerformceAllocScene { public: + CREATE_FUNC(SpriteDeallocTest); + virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void update(float dt); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h index 95ce5914b5..a82e5aba89 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h @@ -7,6 +7,8 @@ class NodeChildrenMenuLayer : public PerformBasicLayer { public: + CREATE_FUNC(NodeChildrenMenuLayer); + NodeChildrenMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); virtual void showCurrentTest(); void dumpProfilerInfo(float dt); @@ -19,6 +21,8 @@ public: class NodeChildrenMainScene : public Scene { public: + CREATE_FUNC(NodeChildrenMainScene); + virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual std::string title(); virtual std::string subtitle(); @@ -44,6 +48,8 @@ protected: class IterateSpriteSheet : public NodeChildrenMainScene { public: + CREATE_FUNC(IterateSpriteSheet); + ~IterateSpriteSheet(); virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); @@ -57,6 +63,8 @@ protected: class IterateSpriteSheetForLoop : public IterateSpriteSheet { public: + CREATE_FUNC(IterateSpriteSheetForLoop); + virtual void update(float dt); virtual std::string title(); @@ -67,6 +75,8 @@ public: class IterateSpriteSheetIterator : public IterateSpriteSheet { public: + CREATE_FUNC(IterateSpriteSheetIterator); + virtual void update(float dt); virtual std::string title(); @@ -77,6 +87,8 @@ public: class IterateSpriteSheetCArray : public IterateSpriteSheet { public: + CREATE_FUNC(IterateSpriteSheetCArray); + virtual void update(float dt); virtual std::string title(); @@ -87,6 +99,8 @@ public: class AddRemoveSpriteSheet : public NodeChildrenMainScene { public: + CREATE_FUNC(AddRemoveSpriteSheet); + ~AddRemoveSpriteSheet(); virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); @@ -106,6 +120,8 @@ protected: class CallFuncsSpriteSheetForEach : public IterateSpriteSheet { public: + CREATE_FUNC(CallFuncsSpriteSheetForEach); + virtual void update(float dt); virtual std::string title(); @@ -116,6 +132,8 @@ public: class CallFuncsSpriteSheetCMacro : public IterateSpriteSheet { public: + CREATE_FUNC(CallFuncsSpriteSheetCMacro); + virtual void update(float dt); virtual std::string title(); @@ -128,6 +146,8 @@ public: class AddSprite : public AddRemoveSpriteSheet { public: + CREATE_FUNC(AddSprite); + virtual void update(float dt); virtual std::string title(); @@ -138,6 +158,8 @@ public: class AddSpriteSheet : public AddRemoveSpriteSheet { public: + CREATE_FUNC(AddSpriteSheet); + virtual void update(float dt); virtual std::string title(); @@ -148,6 +170,8 @@ public: class GetSpriteSheet : public AddRemoveSpriteSheet { public: + CREATE_FUNC(GetSpriteSheet); + virtual void update(float dt); virtual std::string title(); @@ -158,6 +182,8 @@ public: class RemoveSprite : public AddRemoveSpriteSheet { public: + CREATE_FUNC(RemoveSprite); + virtual void update(float dt); virtual std::string title(); @@ -168,6 +194,8 @@ public: class RemoveSpriteSheet : public AddRemoveSpriteSheet { public: + CREATE_FUNC(RemoveSpriteSheet); + virtual void update(float dt); virtual std::string title(); @@ -178,6 +206,8 @@ public: class ReorderSpriteSheet : public AddRemoveSpriteSheet { public: + CREATE_FUNC(ReorderSpriteSheet); + virtual void update(float dt); virtual std::string title(); @@ -188,6 +218,8 @@ public: class SortAllChildrenSpriteSheet : public AddRemoveSpriteSheet { public: + CREATE_FUNC(SortAllChildrenSpriteSheet); + virtual void update(float dt); virtual std::string title(); @@ -198,6 +230,8 @@ public: class VisitSceneGraph : public NodeChildrenMainScene { public: + CREATE_FUNC(VisitSceneGraph); + void initWithQuantityOfNodes(unsigned int nodes) override; virtual void update(float dt) override; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 29f4b68e6d..3ec1e47986 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -26,9 +26,6 @@ namespace sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -40,18 +37,12 @@ namespace sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } static Layer* restart() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index a3ccc76e57..1abf321b59 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -11,6 +11,8 @@ class PhysicsTestScene : public TestScene { public: + CREATE_FUNC(PhysicsTestScene); + virtual bool initTest() override; virtual void runThisTest(); @@ -22,10 +24,9 @@ private: class PhysicsDemo : public BaseTest { -protected: - PhysicsTestScene* _scene; - public: + CREATE_FUNC(PhysicsDemo); + PhysicsDemo(); virtual ~PhysicsDemo(); @@ -48,6 +49,7 @@ public: void onTouchEnded(Touch* touch, Event* event); protected: + PhysicsTestScene* _scene; Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; std::map _mouses; @@ -56,6 +58,8 @@ protected: class PhysicsDemoClickAdd : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoClickAdd); + virtual ~PhysicsDemoClickAdd(); void onEnter() override; std::string subtitle() override; @@ -67,6 +71,8 @@ public: class PhysicsDemoLogoSmash : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoLogoSmash); + void onEnter() override; std::string title() override; }; @@ -74,6 +80,8 @@ public: class PhysicsDemoPlink : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoPlink); + void onEnter() override; std::string title() override; }; @@ -81,8 +89,10 @@ public: class PhysicsDemoRayCast : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoRayCast); + PhysicsDemoRayCast(); -public: + void onEnter() override; std::string title() override; void update(float delta) override; @@ -101,6 +111,8 @@ private: class PhysicsDemoJoints : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoJoints); + void onEnter() override; std::string title() override; }; @@ -108,6 +120,8 @@ public: class PhysicsDemoActions : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoActions); + void onEnter() override; std::string title() override; }; @@ -115,6 +129,8 @@ public: class PhysicsDemoPump : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoPump); + void onEnter() override; void update(float delta) override; std::string title() override; @@ -132,6 +148,8 @@ private: class PhysicsDemoOneWayPlatform : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoOneWayPlatform); + void onEnter() override; std::string title() override; @@ -141,6 +159,8 @@ public: class PhysicsDemoSlice : public PhysicsDemo { public: + CREATE_FUNC(PhysicsDemoSlice); + void onEnter() override; std::string title() override; std::string subtitle() override; diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index d225e1c8f8..0ede17cec3 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -55,9 +55,6 @@ Layer* nextSchedulerTest() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -69,18 +66,12 @@ Layer* backSchedulerTest() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } Layer* restartSchedulerTest() { auto layer = (createFunctions[sceneIdx])(); - layer->init(); - layer->autorelease(); - return layer; } @@ -1098,6 +1089,8 @@ std::string TwoSchedulers::subtitle() class TestNode2 : public Node { public: + CREATE_FUNC(TestNode2); + ~TestNode2() { cocos2d::log("Delete TestNode (should not crash)"); this->unscheduleAllSelectors(); @@ -1111,9 +1104,7 @@ void SchedulerIssue2268::onEnter() { SchedulerTestLayer::onEnter(); - testNode = new TestNode2(); - testNode->init(); - testNode->autorelease(); + testNode = TestNode2::create(); testNode->retain(); testNode->schedule(SEL_SCHEDULE(&TestNode::update)); this->addChild(testNode); diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h index 3e5ba3c9ac..226136cb9c 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h @@ -35,6 +35,8 @@ public: class SchedulerAutoremove : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerAutoremove); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -48,6 +50,8 @@ private: class SchedulerPauseResume : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerPauseResume); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -60,6 +64,8 @@ public: class SchedulerPauseResumeAll : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerPauseResumeAll); + SchedulerPauseResumeAll(); virtual ~SchedulerPauseResumeAll(); virtual void onEnter(); @@ -79,6 +85,8 @@ private: class SchedulerPauseResumeAllUser : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerPauseResumeAllUser); + SchedulerPauseResumeAllUser(); virtual ~SchedulerPauseResumeAllUser(); virtual void onEnter(); @@ -97,6 +105,8 @@ private: class SchedulerUnscheduleAll : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUnscheduleAll); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -111,6 +121,8 @@ public: class SchedulerUnscheduleAllHard : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUnscheduleAllHard); + virtual void onEnter(); virtual void onExit(); virtual std::string title(); @@ -128,6 +140,8 @@ private: class SchedulerUnscheduleAllUserLevel : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUnscheduleAllUserLevel); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -142,6 +156,8 @@ public: class SchedulerSchedulesAndRemove : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerSchedulesAndRemove); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -156,6 +172,8 @@ public: class SchedulerUpdate : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUpdate); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -166,6 +184,8 @@ public: class SchedulerUpdateAndCustom : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUpdateAndCustom); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -178,6 +198,8 @@ public: class SchedulerUpdateFromCustom : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerUpdateFromCustom); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -190,6 +212,8 @@ public: class TestNode : public Node { public: + CREATE_FUNC(TestNode); + ~TestNode(); void initWithString(String* pStr, int priority); @@ -201,6 +225,8 @@ private: class RescheduleSelector : public SchedulerTestLayer { public: + CREATE_FUNC(RescheduleSelector); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -214,6 +240,8 @@ private: class SchedulerDelayAndRepeat : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerDelayAndRepeat); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -223,6 +251,8 @@ public: class SchedulerTimeScale : public SchedulerTestLayer { public: + CREATE_FUNC(SchedulerTimeScale); + void onEnter(); void onExit(); virtual std::string title(); @@ -236,6 +266,8 @@ public: class TwoSchedulers : public SchedulerTestLayer { public: + CREATE_FUNC(TwoSchedulers); + virtual ~TwoSchedulers(); virtual std::string title(); virtual std::string subtitle(); @@ -253,19 +285,24 @@ public: class SchedulerIssue2268 : public SchedulerTestLayer { - public: - ~SchedulerIssue2268(); - std::string title(); - std::string subtitle(); - void onEnter(); - void update(float dt); - private: - Node *testNode; +public: + CREATE_FUNC(SchedulerIssue2268); + + ~SchedulerIssue2268(); + std::string title(); + std::string subtitle(); + void onEnter(); + void update(float dt); + +private: + Node *testNode; }; class SchedulerTestScene : public TestScene { public: + CREATE_FUNC(SchedulerTestScene); + virtual void runThisTest(); }; diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index 38ca0d01a3..5448c31251 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -101,18 +101,11 @@ template class ShaderSpriteCreator { public: - static spriteType* createSprite(const char* pszFileName) + static spriteType* createSprite(const std::string& fileName) { - spriteType* pRet = new spriteType(); - if (pRet && pRet->initWithFile(pszFileName)) - { - pRet->autorelease(); - } - else - { - CC_SAFE_DELETE(pRet); - } - return pRet; + spriteType* ret = spriteType::create(); + ret->setTexture(fileName); + return ret; } }; @@ -236,6 +229,7 @@ void ShaderSprite::draw() class NormalSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(NormalSprite); NormalSprite(); protected: virtual void buildCustomUniforms(); @@ -260,6 +254,7 @@ void NormalSprite::setCustomUniforms() class GreyScaleSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(GreyScaleSprite); GreyScaleSprite(); protected: virtual void buildCustomUniforms(); @@ -284,6 +279,7 @@ void GreyScaleSprite::setCustomUniforms() class BlurSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(BlurSprite); BlurSprite(); void setBlurSize(float f); protected: @@ -331,6 +327,7 @@ void BlurSprite::setBlurSize(float f) class NoiseSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(NoiseSprite); NoiseSprite(); private: @@ -362,6 +359,7 @@ void NoiseSprite::setCustomUniforms() class EdgeDetectionSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(EdgeDetectionSprite); EdgeDetectionSprite(); private: @@ -393,6 +391,7 @@ void EdgeDetectionSprite::setCustomUniforms() class BloomSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(BloomSprite); BloomSprite(); private: @@ -424,6 +423,7 @@ void BloomSprite::setCustomUniforms() class CelShadingSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(CelShadingSprite); CelShadingSprite(); private: @@ -455,6 +455,7 @@ void CelShadingSprite::setCustomUniforms() class LensFlareSprite : public ShaderSprite, public ShaderSpriteCreator { public: + CREATE_FUNC(LensFlareSprite); LensFlareSprite(); private: diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index cade29ab94..6a7ee63d7d 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -c37b913119295ed7f6bcbb7e04cce322722ea1a5 \ No newline at end of file +386b62dbb6c45199cb3d4e6a4f8528fa530e283c \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index 4f7614f701..80939911a5 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -40,17 +40,14 @@ void TestScene::onEnter() outside the scope. So I choose the (2) solution. Commented by James Chen. */ -// auto scene = Scene::create(); - auto scene = new Scene(); - if (scene && scene->init()) - { - auto layer = new TestController(); - scene->addChild(layer); - layer->release(); - Director::getInstance()->replaceScene(scene); - scene->release(); - } - + auto scene = Scene::create(); + + auto layer = new TestController(); + scene->addChild(layer); + layer->release(); + + Director::getInstance()->replaceScene(scene); + cocostudio::ArmatureDataManager::destoryInstance(); }); diff --git a/samples/Cpp/TestCpp/Classes/testBasic.h b/samples/Cpp/TestCpp/Classes/testBasic.h index 771fd1a5a5..68caa0d839 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.h +++ b/samples/Cpp/TestCpp/Classes/testBasic.h @@ -27,6 +27,6 @@ static Layer* create##className() \ // C++ 11 -#define CL(__className__) [](){ return new __className__();} +#define CL(__className__) [](){ return __className__::create();} #endif From 2ce2eaf4b32038a87a73c66642d893f091bd59d6 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 13 Nov 2013 17:36:33 -0800 Subject: [PATCH 02/75] More tests converted --- .../ClippingNodeTest/ClippingNodeTest.cpp | 9 +-- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 6 -- .../Cpp/TestCpp/Classes/LabelTest/LabelTest.h | 67 +++++++++++++++- .../Classes/LabelTest/LabelTestNew.cpp | 6 -- .../TestCpp/Classes/LabelTest/LabelTestNew.h | 47 ++++++++++- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 39 ++++----- .../Cpp/TestCpp/Classes/LayerTest/LayerTest.h | 18 +++++ .../MotionStreakTest/MotionStreakTest.cpp | 6 -- .../MotionStreakTest/MotionStreakTest.h | 4 + .../NewEventDispatcherTest.cpp | 8 +- .../NewEventDispatcherTest.h | 8 ++ .../PerformanceNodeChildrenTest.h | 9 +-- .../RenderTextureTest/RenderTextureTest.cpp | 6 -- .../RenderTextureTest/RenderTextureTest.h | 16 ++-- .../Classes/ShaderTest/ShaderTest2.cpp | 54 +++++-------- .../TestCpp/Classes/ShaderTest/ShaderTest2.h | 15 +++- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../TestCpp/Classes/SpriteTest/SpriteTest.h | 79 +++++++++++++++++++ 18 files changed, 287 insertions(+), 112 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index bec4eddd83..84bbf9eb15 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -113,26 +113,23 @@ std::string BaseClippingNodeTest::subtitle() void BaseClippingNodeTest::restartCallback(Object* sender) { - Scene *s = new ClippingNodeTestScene(); + Scene *s = ClippingNodeTestScene::create(); s->addChild(restartAction()); Director::getInstance()->replaceScene(s); - s->release(); } void BaseClippingNodeTest::nextCallback(Object* sender) { - Scene *s = new ClippingNodeTestScene(); + Scene *s = ClippingNodeTestScene::create(); s->addChild(nextAction()); Director::getInstance()->replaceScene(s); - s->release(); } void BaseClippingNodeTest::backCallback(Object* sender) { - Scene *s = new ClippingNodeTestScene(); + Scene *s = ClippingNodeTestScene::create(); s->addChild(backAction()); Director::getInstance()->replaceScene(s); - s->release(); } void BaseClippingNodeTest::setup() diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index ea9405eabe..ea1333b172 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -82,8 +82,6 @@ Layer* nextAtlasAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } @@ -95,16 +93,12 @@ Layer* backAtlasAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } Layer* restartAtlasAction() { auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h index 87ff938c97..eafe528cf8 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h @@ -10,6 +10,8 @@ class AtlasDemo : public BaseTest protected: public: + CREATE_FUNC(AtlasDemo); + AtlasDemo(void); ~AtlasDemo(void); @@ -27,6 +29,8 @@ class Atlas1 : public AtlasDemo { TextureAtlas* _textureAtlas; public: + CREATE_FUNC(Atlas1); + Atlas1(); ~Atlas1(); virtual std::string title(); @@ -38,6 +42,8 @@ class LabelAtlasTest : public AtlasDemo { float _time; public: + CREATE_FUNC(LabelAtlasTest); + LabelAtlasTest(); virtual void step(float dt); @@ -50,6 +56,8 @@ class LabelAtlasColorTest : public AtlasDemo { float _time; public: + CREATE_FUNC(LabelAtlasColorTest); + LabelAtlasColorTest(); virtual void step(float dt); virtual std::string title(); @@ -60,6 +68,8 @@ public: class LabelTTFAlignment : public AtlasDemo { public: + CREATE_FUNC(LabelTTFAlignment); + LabelTTFAlignment(); virtual std::string title(); virtual std::string subtitle(); @@ -70,6 +80,8 @@ class Atlas3 : public AtlasDemo { float _time; public: + CREATE_FUNC(Atlas3); + Atlas3(); virtual void step(float dt); @@ -82,6 +94,8 @@ class Atlas4 : public AtlasDemo { float _time; public: + CREATE_FUNC(Atlas4); + Atlas4(); virtual void step(float dt); virtual void draw(); @@ -93,6 +107,8 @@ public: class Atlas5 : public AtlasDemo { public: + CREATE_FUNC(Atlas5); + Atlas5(); virtual std::string title(); virtual std::string subtitle(); @@ -102,6 +118,8 @@ public: class Atlas6 : public AtlasDemo { public: + CREATE_FUNC(Atlas6); + Atlas6(); virtual std::string title(); virtual std::string subtitle(); @@ -110,6 +128,8 @@ public: class AtlasBitmapColor : public AtlasDemo { public: + CREATE_FUNC(AtlasBitmapColor); + AtlasBitmapColor(); virtual std::string title(); @@ -119,6 +139,8 @@ public: class AtlasFastBitmap : public AtlasDemo { public: + CREATE_FUNC(AtlasFastBitmap); + AtlasFastBitmap(); virtual std::string title(); virtual std::string subtitle(); @@ -127,6 +149,8 @@ public: class BitmapFontMultiLine : public AtlasDemo { public: + CREATE_FUNC(BitmapFontMultiLine); + BitmapFontMultiLine(); virtual std::string title(); virtual std::string subtitle(); @@ -135,6 +159,8 @@ public: class LabelsEmpty : public AtlasDemo { public: + CREATE_FUNC(LabelsEmpty); + LabelsEmpty(); void updateStrings(float dt); virtual std::string title(); @@ -147,6 +173,8 @@ private: class LabelBMFontHD : public AtlasDemo { public: + CREATE_FUNC(LabelBMFontHD); + LabelBMFontHD(); virtual std::string title(); virtual std::string subtitle(); @@ -155,6 +183,8 @@ public: class LabelAtlasHD : public AtlasDemo { public: + CREATE_FUNC(LabelAtlasHD); + LabelAtlasHD(); virtual std::string title(); virtual std::string subtitle(); @@ -163,6 +193,8 @@ public: class LabelGlyphDesigner : public AtlasDemo { public: + CREATE_FUNC(LabelGlyphDesigner); + LabelGlyphDesigner(); virtual std::string title(); virtual std::string subtitle(); @@ -171,12 +203,16 @@ public: class AtlasTestScene : public TestScene { public: + CREATE_FUNC(AtlasTestScene); + virtual void runThisTest(); }; class LabelTTFTest : public AtlasDemo { public: + CREATE_FUNC(LabelTTFTest); + LabelTTFTest(); virtual ~LabelTTFTest(); virtual std::string title(); @@ -199,6 +235,8 @@ private: class LabelTTFMultiline : public AtlasDemo { public: + CREATE_FUNC(LabelTTFMultiline); + LabelTTFMultiline(); virtual std::string title(); virtual std::string subtitle(); @@ -207,6 +245,8 @@ public: class LabelTTFChinese : public AtlasDemo { public: + CREATE_FUNC(LabelTTFChinese); + LabelTTFChinese(); virtual std::string title(); }; @@ -214,6 +254,8 @@ public: class LabelBMFontChinese : public AtlasDemo { public: + CREATE_FUNC(LabelBMFontChinese); + LabelBMFontChinese(); virtual std::string title(); }; @@ -221,6 +263,8 @@ public: class BitmapFontMultiLineAlignment : public AtlasDemo { public: + CREATE_FUNC(BitmapFontMultiLineAlignment); + BitmapFontMultiLineAlignment(); ~BitmapFontMultiLineAlignment(); void snapArrowsToEdge(); @@ -243,6 +287,8 @@ public: class LabelTTFA8Test : public AtlasDemo { public: + CREATE_FUNC(LabelTTFA8Test); + LabelTTFA8Test(); virtual std::string title(); @@ -252,6 +298,8 @@ public: class BMFontOneAtlas : public AtlasDemo { public: + CREATE_FUNC(BMFontOneAtlas); + BMFontOneAtlas(); virtual std::string title(); @@ -261,6 +309,8 @@ public: class BMFontUnicode : public AtlasDemo { public: + CREATE_FUNC(BMFontUnicode); + BMFontUnicode(); virtual std::string title(); @@ -270,6 +320,8 @@ public: class BMFontInit : public AtlasDemo { public: + CREATE_FUNC(BMFontInit); + BMFontInit(); virtual std::string title(); @@ -279,6 +331,8 @@ public: class TTFFontInit : public AtlasDemo { public: + CREATE_FUNC(TTFFontInit); + TTFFontInit(); virtual std::string title(); @@ -288,6 +342,8 @@ public: class TTFFontShadowAndStroke : public AtlasDemo { public: + CREATE_FUNC(TTFFontShadowAndStroke); + TTFFontShadowAndStroke(); virtual std::string title(); @@ -298,6 +354,8 @@ public: class Issue1343 : public AtlasDemo { public: + CREATE_FUNC(Issue1343); + Issue1343(); virtual std::string title(); @@ -307,6 +365,8 @@ public: class LabelBMFontBounds : public AtlasDemo { public: + CREATE_FUNC(LabelBMFontBounds); + LabelBMFontBounds(); virtual void draw(); @@ -319,7 +379,8 @@ private: class NewLabelTTFUnicode : public AtlasDemo { public: - + CREATE_FUNC(NewLabelTTFUnicode); + NewLabelTTFUnicode(); virtual std::string title(); @@ -329,6 +390,7 @@ public: class NewLabelBMFontTest : public AtlasDemo { public: + CREATE_FUNC(NewLabelBMFontTest); NewLabelBMFontTest(); @@ -341,6 +403,7 @@ private: class NewLabelFontDefTest : public AtlasDemo { public: + CREATE_FUNC(NewLabelFontDefTest); NewLabelFontDefTest(); @@ -353,6 +416,8 @@ private: class LabelBMFontCrashTest : public AtlasDemo { public: + CREATE_FUNC(LabelBMFontCrashTest); + virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index e329dafcbe..b6540c8ab8 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -74,8 +74,6 @@ Layer* nextAtlasActionNew() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } @@ -87,16 +85,12 @@ Layer* backAtlasActionNew() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } Layer* restartAtlasActionNew() { auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h index d494858ffa..03e94cc682 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h @@ -10,6 +10,8 @@ class AtlasDemoNew : public BaseTest protected: public: + CREATE_FUNC(AtlasDemoNew); + AtlasDemoNew(void); ~AtlasDemoNew(void); @@ -25,6 +27,8 @@ public: class LabelTTFAlignmentNew : public AtlasDemoNew { public: + CREATE_FUNC(LabelTTFAlignmentNew); + LabelTTFAlignmentNew(); virtual std::string title(); virtual std::string subtitle(); @@ -34,6 +38,8 @@ class LabelFNTColorAndOpacity : public AtlasDemoNew { float _time; public: + CREATE_FUNC(LabelFNTColorAndOpacity); + LabelFNTColorAndOpacity(); virtual void step(float dt); @@ -46,6 +52,8 @@ class LabelFNTSpriteActions : public AtlasDemoNew { float _time; public: + CREATE_FUNC(LabelFNTSpriteActions); + LabelFNTSpriteActions(); virtual void step(float dt); virtual void draw(); @@ -57,6 +65,8 @@ public: class LabelFNTPadding : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTPadding); + LabelFNTPadding(); virtual std::string title(); virtual std::string subtitle(); @@ -66,6 +76,8 @@ public: class LabelFNTOffset : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTOffset); + LabelFNTOffset(); virtual std::string title(); virtual std::string subtitle(); @@ -74,6 +86,8 @@ public: class LabelFNTColor : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTColor); + LabelFNTColor(); virtual std::string title(); @@ -83,6 +97,8 @@ public: class LabelFNTHundredLabels : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTHundredLabels); + LabelFNTHundredLabels(); virtual std::string title(); virtual std::string subtitle(); @@ -91,6 +107,8 @@ public: class LabelFNTMultiLine : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTMultiLine); + LabelFNTMultiLine(); virtual std::string title(); virtual std::string subtitle(); @@ -99,6 +117,8 @@ public: class LabelFNTandTTFEmpty : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTandTTFEmpty); + LabelFNTandTTFEmpty(); void updateStrings(float dt); virtual std::string title(); @@ -111,6 +131,8 @@ private: class LabelFNTRetina : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTRetina); + LabelFNTRetina(); virtual std::string title(); virtual std::string subtitle(); @@ -119,6 +141,8 @@ public: class LabelFNTGlyphDesigner : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTGlyphDesigner); + LabelFNTGlyphDesigner(); virtual std::string title(); virtual std::string subtitle(); @@ -127,12 +151,16 @@ public: class AtlasTestSceneNew : public TestScene { public: + CREATE_FUNC(AtlasTestSceneNew); + virtual void runThisTest(); }; class LabelTTFUnicodeChinese : public AtlasDemoNew { public: + CREATE_FUNC(LabelTTFUnicodeChinese); + LabelTTFUnicodeChinese(); virtual std::string title(); virtual std::string subtitle(); @@ -141,6 +169,8 @@ public: class LabelFNTUnicodeChinese : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTUnicodeChinese); + LabelFNTUnicodeChinese(); virtual std::string title(); virtual std::string subtitle(); @@ -149,6 +179,8 @@ public: class LabelFNTMultiLineAlignment : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTMultiLineAlignment); + LabelFNTMultiLineAlignment(); ~LabelFNTMultiLineAlignment(); void snapArrowsToEdge(); @@ -171,6 +203,8 @@ public: class LabelFNTUNICODELanguages : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTUNICODELanguages); + LabelFNTUNICODELanguages(); virtual std::string title(); @@ -180,6 +214,8 @@ public: class LabelFNTBounds : public AtlasDemoNew { public: + CREATE_FUNC(LabelFNTBounds); + LabelFNTBounds(); virtual void draw(); @@ -192,6 +228,7 @@ private: class LabelTTFLongLineWrapping : public AtlasDemoNew { public: + CREATE_FUNC(LabelTTFLongLineWrapping); LabelTTFLongLineWrapping(); @@ -202,6 +239,7 @@ public: class LabelTTFColor : public AtlasDemoNew { public: + CREATE_FUNC(LabelTTFColor); LabelTTFColor(); @@ -212,7 +250,8 @@ public: class LabelTTFUnicodeNew : public AtlasDemoNew { public: - + CREATE_FUNC(LabelTTFUnicodeNew); + LabelTTFUnicodeNew(); virtual std::string title(); @@ -222,7 +261,8 @@ public: class LabelTTFDynamicAlignment : public AtlasDemoNew { public: - + CREATE_FUNC(LabelTTFDynamicAlignment); + LabelTTFDynamicAlignment(); virtual std::string title(); virtual std::string subtitle(); @@ -243,6 +283,7 @@ private: class LabelTTFFontsTestNew : public AtlasDemoNew { public: + CREATE_FUNC(LabelTTFFontsTestNew); LabelTTFFontsTestNew(); @@ -254,6 +295,7 @@ public: class LabelBMFontTestNew : public AtlasDemoNew { public: + CREATE_FUNC(LabelBMFontTestNew); LabelBMFontTestNew(); @@ -266,6 +308,7 @@ private: class LabelFontDefTestNew : public AtlasDemoNew { public: + CREATE_FUNC(LabelFontDefTestNew); LabelFontDefTestNew(); diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index 581928a4f3..0d10234a62 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -33,9 +33,7 @@ static Layer* nextAction() sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; - auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - + auto layer = (createFunctions[sceneIdx])(); return layer; } @@ -47,16 +45,12 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } @@ -156,23 +150,22 @@ void LayerTestCascadingOpacityA::onEnter() label->setPosition( Point( s.width/2, s.height/2)); layer1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(4, 0), - FadeTo::create(4, 255), - DelayTime::create(1), - NULL))); - + RepeatForever::create( + Sequence::create( + FadeTo::create(4, 0), + FadeTo::create(4, 255), + DelayTime::create(1), + NULL))); + sister1->runAction( - RepeatForever::create( - Sequence::create( - FadeTo::create(2, 0), - FadeTo::create(2, 255), - FadeTo::create(2, 0), - FadeTo::create(2, 255), - DelayTime::create(1), - NULL))); - + RepeatForever::create( + Sequence::create( + FadeTo::create(2, 0), + FadeTo::create(2, 255), + FadeTo::create(2, 0), + FadeTo::create(2, 255), + DelayTime::create(1), + NULL))); // Enable cascading in scene setEnableRecursiveCascading(this, true); diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h index dd381b001f..f54173cea5 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h @@ -26,6 +26,7 @@ public: class LayerTestCascadingOpacityA : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingOpacityA); virtual void onEnter(); virtual std::string title(); }; @@ -33,6 +34,7 @@ public: class LayerTestCascadingOpacityB : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingOpacityB); virtual void onEnter(); virtual std::string title(); }; @@ -40,6 +42,7 @@ public: class LayerTestCascadingOpacityC : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingOpacityC); virtual void onEnter(); virtual std::string title(); }; @@ -47,6 +50,7 @@ public: class LayerTestCascadingColorA : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingColorA); virtual void onEnter(); virtual std::string title(); }; @@ -54,6 +58,7 @@ public: class LayerTestCascadingColorB : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingColorB); virtual void onEnter(); virtual std::string title(); }; @@ -61,6 +66,7 @@ public: class LayerTestCascadingColorC : public LayerTest { public: + CREATE_FUNC(LayerTestCascadingColorC); virtual void onEnter(); virtual std::string title(); }; @@ -69,6 +75,8 @@ public: class LayerTest1 : public LayerTest { public: + CREATE_FUNC(LayerTest1); + virtual void onEnter(); virtual std::string title(); @@ -82,6 +90,7 @@ public: class LayerTest2 : public LayerTest { public: + CREATE_FUNC(LayerTest2); virtual void onEnter(); virtual std::string title(); }; @@ -90,6 +99,8 @@ public: class LayerTestBlend : public LayerTest { public: + CREATE_FUNC(LayerTestBlend); + LayerTestBlend(); void newBlend(float dt); virtual std::string title(); @@ -98,6 +109,7 @@ public: class LayerGradientTest : public LayerTest { public: + CREATE_FUNC(LayerGradientTest); LayerGradientTest(); void onTouchesMoved(const std::vector& touches, Event *event); virtual std::string title(); @@ -108,6 +120,7 @@ public: class LayerGradientTest2 : public LayerTest { public: + CREATE_FUNC(LayerGradientTest2); LayerGradientTest2(); virtual std::string title(); virtual std::string subtitle(); @@ -116,6 +129,7 @@ public: class LayerGradientTest3 : public LayerTest { public: + CREATE_FUNC(LayerGradientTest3); LayerGradientTest3(); virtual std::string title(); virtual std::string subtitle(); @@ -124,6 +138,7 @@ public: class LayerIgnoreAnchorPointPos : public LayerTest { public: + CREATE_FUNC(LayerIgnoreAnchorPointPos); virtual void onEnter(); void onToggle(Object* pObject); virtual std::string title(); @@ -133,6 +148,7 @@ public: class LayerIgnoreAnchorPointRot : public LayerTest { public: + CREATE_FUNC(LayerIgnoreAnchorPointRot); virtual void onEnter(); void onToggle(Object* pObject); virtual std::string title(); @@ -142,6 +158,7 @@ public: class LayerIgnoreAnchorPointScale : public LayerTest { public: + CREATE_FUNC(LayerIgnoreAnchorPointScale); virtual void onEnter(); void onToggle(Object* pObject); virtual std::string title(); @@ -151,6 +168,7 @@ public: class LayerExtendedBlendOpacityTest : public LayerTest { public: + CREATE_FUNC(LayerExtendedBlendOpacityTest); LayerExtendedBlendOpacityTest(); virtual std::string title(); virtual std::string subtitle(); diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp index 9d9057c3e7..cdff3e3382 100644 --- a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp @@ -28,8 +28,6 @@ Layer* nextMotionAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } @@ -41,16 +39,12 @@ Layer* backMotionAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } Layer* restartMotionAction() { auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } //------------------------------------------------------------------ diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h index a45eccfc01..5030ec9f3d 100644 --- a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h +++ b/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h @@ -32,6 +32,7 @@ protected: Node* _target; public: + CREATE_FUNC(MotionStreakTest1); virtual void onEnter(); void onUpdate(float delta); virtual std::string title(); @@ -44,6 +45,7 @@ protected: Node* _target; public: + CREATE_FUNC(MotionStreakTest2); virtual void onEnter(); void onTouchesMoved(const std::vector& touches, Event* event); virtual std::string title(); @@ -52,6 +54,8 @@ public: class Issue1358 : public MotionStreakTest { public: + CREATE_FUNC(Issue1358); + virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index a9ff786e4a..4b4904a847 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -28,13 +28,7 @@ unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[ int sceneIdx=-1; Layer* createTest(int index) { - auto layer = (createFunctions[index])();; - - if (layer) - { - layer->autorelease(); - } - + auto layer = (createFunctions[index])();; return layer; } diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 529813e7b8..c326e9446a 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -34,6 +34,7 @@ public: class TouchableSpriteTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(TouchableSpriteTest); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -42,6 +43,7 @@ public: class FixedPriorityTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(FixedPriorityTest); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -50,6 +52,7 @@ public: class RemoveListenerWhenDispatching : public EventDispatcherTestDemo { public: + CREATE_FUNC(RemoveListenerWhenDispatching); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -58,6 +61,7 @@ public: class CustomEventTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(CustomEventTest); virtual void onEnter() override; virtual void onExit() override; virtual std::string title() override; @@ -70,6 +74,7 @@ private: class LabelKeyboardEventTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(LabelKeyboardEventTest); virtual void onEnter() override; virtual std::string title() override; virtual std::string subtitle() override; @@ -78,6 +83,7 @@ public: class SpriteAccelerationEventTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(SpriteAccelerationEventTest); virtual void onEnter() override; virtual void onExit() override; virtual std::string title() override; @@ -87,6 +93,7 @@ public: class RemoveAndRetainNodeTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(RemoveAndRetainNodeTest); virtual void onEnter() override; virtual void onExit() override; virtual std::string title() override; @@ -99,6 +106,7 @@ private: class RemoveListenerAfterAddingTest : public EventDispatcherTestDemo { public: + CREATE_FUNC(RemoveListenerAfterAddingTest); virtual void onEnter() override; virtual void onExit() override; virtual std::string title() override; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h index a82e5aba89..a38796635d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h @@ -9,6 +9,7 @@ class NodeChildrenMenuLayer : public PerformBasicLayer public: CREATE_FUNC(NodeChildrenMenuLayer); + NodeChildrenMenuLayer(); NodeChildrenMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); virtual void showCurrentTest(); void dumpProfilerInfo(float dt); @@ -21,8 +22,6 @@ public: class NodeChildrenMainScene : public Scene { public: - CREATE_FUNC(NodeChildrenMainScene); - virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual std::string title(); virtual std::string subtitle(); @@ -48,8 +47,6 @@ protected: class IterateSpriteSheet : public NodeChildrenMainScene { public: - CREATE_FUNC(IterateSpriteSheet); - ~IterateSpriteSheet(); virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); @@ -65,6 +62,7 @@ class IterateSpriteSheetForLoop : public IterateSpriteSheet public: CREATE_FUNC(IterateSpriteSheetForLoop); + IterateSpriteSheetForLoop() {} virtual void update(float dt); virtual std::string title(); @@ -77,6 +75,7 @@ class IterateSpriteSheetIterator : public IterateSpriteSheet public: CREATE_FUNC(IterateSpriteSheetIterator); + IterateSpriteSheetIterator() {} virtual void update(float dt); virtual std::string title(); @@ -99,8 +98,6 @@ public: class AddRemoveSpriteSheet : public NodeChildrenMainScene { public: - CREATE_FUNC(AddRemoveSpriteSheet); - ~AddRemoveSpriteSheet(); virtual void updateQuantityOfNodes(); virtual void initWithQuantityOfNodes(unsigned int nNodes); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 987d8b8f05..d305c0382b 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -24,8 +24,6 @@ static Layer* nextTestCase() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } @@ -37,16 +35,12 @@ static Layer* backTestCase() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } static Layer* restartTestCase() { auto layer = (createFunctions[sceneIdx])(); - layer->autorelease(); - return layer; } diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h index afd985ec70..cedf516f3f 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h @@ -20,6 +20,7 @@ public: class RenderTextureSave : public RenderTextureTest { public: + CREATE_FUNC(RenderTextureSave); RenderTextureSave(); ~RenderTextureSave(); virtual std::string title(); @@ -36,6 +37,7 @@ private: class RenderTextureIssue937 : public RenderTextureTest { public: + CREATE_FUNC(RenderTextureIssue937); RenderTextureIssue937(); virtual std::string title(); virtual std::string subtitle(); @@ -50,6 +52,7 @@ public: class RenderTextureZbuffer : public RenderTextureTest { public: + CREATE_FUNC(RenderTextureZbuffer); RenderTextureZbuffer(); void onTouchesMoved(const std::vector& touches, Event* event); @@ -77,6 +80,7 @@ private: class RenderTextureTestDepthStencil : public RenderTextureTest { public: + CREATE_FUNC(RenderTextureTestDepthStencil); RenderTextureTestDepthStencil(); virtual std::string title(); virtual std::string subtitle(); @@ -88,6 +92,7 @@ private: cocos2d::Sprite *sprite1, *sprite2; cocos2d::RenderTexture *renderTexture; public: + CREATE_FUNC(RenderTextureTargetNode); RenderTextureTargetNode(); virtual void update(float t); @@ -101,19 +106,20 @@ class SpriteRenderTextureBug : public RenderTextureTest { public: -class SimpleSprite : public Sprite -{ + class SimpleSprite : public Sprite + { public: + static SimpleSprite* create(const char* filename, const Rect &rect); SimpleSprite(); virtual void draw(); - static SimpleSprite* create(const char* filename, const Rect &rect); - + public: RenderTexture *rt; -}; + }; public: + CREATE_FUNC(SpriteRenderTextureBug); SpriteRenderTextureBug(); void onTouchesEnded(const std::vector& touches, Event* event); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index 5448c31251..de753d2b18 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -23,12 +23,6 @@ namespace ShaderTest2 Layer* createTest(int index) { auto layer = (createFunctions[index])();; - - if (layer) - { - layer->autorelease(); - } - return layer; } @@ -67,27 +61,23 @@ ShaderTestDemo2::ShaderTestDemo2() void ShaderTestDemo2::backCallback(Object* sender) { - auto s = new ShaderTestScene2(); + auto s = ShaderTestScene2::create(); s->addChild( ShaderTest2::backAction() ); Director::getInstance()->replaceScene(s); - s->release(); } void ShaderTestDemo2::nextCallback(Object* sender) { - auto s = new ShaderTestScene2();//CCScene::create(); + auto s = ShaderTestScene2::create(); s->addChild( ShaderTest2::nextAction() ); Director::getInstance()->replaceScene(s); - s->release(); } void ShaderTestDemo2::restartCallback(Object* sender) { - auto s = new ShaderTestScene2(); - s->addChild(ShaderTest2::restartAction()); - + auto s = ShaderTestScene2::create(); + s->addChild(ShaderTest2::restartAction()); Director::getInstance()->replaceScene(s); - s->release(); } void ShaderTestScene2::runThisTest() @@ -101,10 +91,12 @@ template class ShaderSpriteCreator { public: - static spriteType* createSprite(const std::string& fileName) + static spriteType* createSprite(const std::string& filename) { spriteType* ret = spriteType::create(); - ret->setTexture(fileName); + ret->setTexture(filename); + ret->initShader(); + ret->setBackgroundNotification(); return ret; } }; @@ -115,9 +107,10 @@ public: ShaderSprite(); ~ShaderSprite(); - bool initWithTexture(Texture2D* texture, const Rect& rect); + virtual void initShader(); + void setBackgroundNotification(); + void draw(); - void initProgram(); void listenBackToForeground(Object *obj); protected: @@ -140,30 +133,21 @@ ShaderSprite::~ShaderSprite() void ShaderSprite::listenBackToForeground(Object *obj) { setShaderProgram(NULL); - initProgram(); + initShader(); } -bool ShaderSprite::initWithTexture(Texture2D* texture, const Rect& rect) +void ShaderSprite::setBackgroundNotification() { - if( Sprite::initWithTexture(texture, rect) ) - { - NotificationCenter::getInstance()->addObserver(this, - callfuncO_selector(ShaderSprite::listenBackToForeground), - EVNET_COME_TO_FOREGROUND, - NULL); - - this->initProgram(); - - return true; - } - - return false; + NotificationCenter::getInstance()->addObserver(this, + callfuncO_selector(ShaderSprite::listenBackToForeground), + EVNET_COME_TO_FOREGROUND, + NULL); } -void ShaderSprite::initProgram() +void ShaderSprite::initShader() { GLchar * fragSource = (GLchar*) String::createWithContentsOfFile( - FileUtils::getInstance()->fullPathForFilename(_fragSourceFile.c_str()).c_str())->getCString(); + FileUtils::getInstance()->fullPathForFilename(_fragSourceFile).c_str())->getCString(); auto pProgram = new GLProgram(); pProgram->initWithVertexShaderByteArray(ccPositionTextureColor_vert, fragSource); setShaderProgram(pProgram); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h index 95ddbc592d..7266b552e7 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h @@ -14,19 +14,19 @@ public: void restartCallback(Object* sender); void nextCallback(Object* sender); void backCallback(Object* sender); - - CREATE_FUNC(ShaderTestDemo2); }; class ShaderTestScene2 : public TestScene { public: + CREATE_FUNC(ShaderTestScene2); virtual void runThisTest(); }; class NormalSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(NormalSpriteTest); NormalSpriteTest(); virtual std::string subtitle() {return "NormalSpriteTest";} @@ -35,6 +35,7 @@ public: class GreyScaleSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(GreyScaleSpriteTest); GreyScaleSpriteTest(); virtual std::string subtitle() {return "GreyScaleSpriteTest";} @@ -43,6 +44,7 @@ public: class BlurSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(BlurSpriteTest); BlurSpriteTest(); virtual std::string subtitle() {return "BlurSpriteTest";} @@ -51,6 +53,7 @@ public: class NoiseSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(NoiseSpriteTest); NoiseSpriteTest(); virtual std::string subtitle() {return "NoiseSpriteTest";} }; @@ -58,6 +61,8 @@ public: class EdgeDetectionSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(EdgeDetectionSpriteTest); + EdgeDetectionSpriteTest(); virtual std::string subtitle() {return "EdgeDetectionSpriteTest";} }; @@ -65,6 +70,8 @@ public: class BloomSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(BloomSpriteTest); + BloomSpriteTest(); virtual std::string subtitle() {return "BloomSpriteTest";} }; @@ -72,6 +79,8 @@ public: class LensFlareSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(LensFlareSpriteTest); + LensFlareSpriteTest(); virtual std::string subtitle() {return "LensFlareSpriteTest";} }; @@ -79,6 +88,8 @@ public: class CelShadingSpriteTest : public ShaderTestDemo2 { public: + CREATE_FUNC(CelShadingSpriteTest); + CelShadingSpriteTest(); virtual std::string subtitle() {return "CelShadingSpriteTest";} }; diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 6a7ee63d7d..8786750620 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -386b62dbb6c45199cb3d4e6a4f8528fa530e283c \ No newline at end of file +406ff5d69f664d6e2b597c4f54a0db775087fb65 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h index ca08fb64e3..f09a9091f5 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h @@ -27,6 +27,7 @@ public: class Sprite1 : public SpriteTestDemo { public: + CREATE_FUNC(Sprite1); Sprite1(); virtual std::string title(); @@ -37,6 +38,7 @@ public: class SpriteBatchNode1: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNode1); SpriteBatchNode1(); void addNewSpriteWithCoords(Point p); void onTouchesEnded(const std::vector& touches, Event* event); @@ -46,6 +48,7 @@ public: class SpriteColorOpacity : public SpriteTestDemo { public: + CREATE_FUNC(SpriteColorOpacity); SpriteColorOpacity(); void removeAndAddSprite(float dt); virtual std::string title(); @@ -54,6 +57,8 @@ public: class SpriteBatchNodeColorOpacity : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeColorOpacity); + SpriteBatchNodeColorOpacity(); void removeAndAddSprite(float dt); virtual std::string title(); @@ -63,6 +68,8 @@ class SpriteZOrder : public SpriteTestDemo { int _dir; public: + CREATE_FUNC(SpriteZOrder); + SpriteZOrder(); void reorderSprite(float dt); virtual std::string title(); @@ -72,6 +79,8 @@ class SpriteBatchNodeZOrder: public SpriteTestDemo { int _dir; public: + CREATE_FUNC(SpriteBatchNodeZOrder); + SpriteBatchNodeZOrder(); void reorderSprite(float dt); virtual std::string title(); @@ -80,6 +89,8 @@ public: class SpriteBatchNodeReorder : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorder); + SpriteBatchNodeReorder(); virtual std::string title(); std::string subtitle(); @@ -88,6 +99,8 @@ public: class SpriteBatchNodeReorderIssue744: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorderIssue744); + SpriteBatchNodeReorderIssue744(); virtual std::string title(); std::string subtitle(); @@ -96,6 +109,8 @@ public: class SpriteBatchNodeReorderIssue766 : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorderIssue766); + SpriteBatchNodeReorderIssue766(); virtual std::string title(); virtual std::string subtitle(); @@ -112,6 +127,8 @@ private: class SpriteBatchNodeReorderIssue767 : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorderIssue767); + SpriteBatchNodeReorderIssue767(); virtual std::string title(); virtual std::string subtitle(); @@ -123,6 +140,8 @@ class SpriteZVertex: public SpriteTestDemo int _dir; float _time; public: + CREATE_FUNC(SpriteZVertex); + virtual void onEnter(); virtual void onExit(); SpriteZVertex(); @@ -134,6 +153,8 @@ class SpriteBatchNodeZVertex: public SpriteTestDemo int _dir; float _time; public: + CREATE_FUNC(SpriteBatchNodeZVertex); + virtual void onEnter(); virtual void onExit(); SpriteBatchNodeZVertex(); @@ -143,6 +164,8 @@ public: class SpriteAnchorPoint : public SpriteTestDemo { public: + CREATE_FUNC(SpriteAnchorPoint); + SpriteAnchorPoint(); virtual std::string title(); }; @@ -150,6 +173,8 @@ public: class SpriteBatchNodeAnchorPoint : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeAnchorPoint); + SpriteBatchNodeAnchorPoint(); virtual std::string title(); }; @@ -157,6 +182,8 @@ public: class Sprite6 : public SpriteTestDemo { public: + CREATE_FUNC(Sprite6); + Sprite6(); virtual std::string title(); }; @@ -164,6 +191,8 @@ public: class SpriteFlip : public SpriteTestDemo { public: + CREATE_FUNC(SpriteFlip); + SpriteFlip(); void flipSprites(float dt); virtual std::string title(); @@ -172,6 +201,7 @@ public: class SpriteBatchNodeFlip : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeFlip); SpriteBatchNodeFlip(); void flipSprites(float dt); virtual std::string title(); @@ -180,6 +210,7 @@ public: class SpriteAliased : public SpriteTestDemo { public: + CREATE_FUNC(SpriteAliased); SpriteAliased(); virtual void onEnter(); virtual void onExit(); @@ -189,6 +220,7 @@ public: class SpriteBatchNodeAliased : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeAliased); SpriteBatchNodeAliased(); virtual void onEnter(); virtual void onExit(); @@ -202,6 +234,7 @@ class SpriteNewTexture : public SpriteTestDemo Texture2D* _texture2; public: + CREATE_FUNC(SpriteNewTexture); SpriteNewTexture(); virtual ~SpriteNewTexture(); void addNewSprite(); @@ -215,6 +248,7 @@ class SpriteBatchNodeNewTexture : public SpriteTestDemo Texture2D* _texture2; public: + CREATE_FUNC(SpriteBatchNodeNewTexture); SpriteBatchNodeNewTexture(); virtual ~SpriteBatchNodeNewTexture(); void addNewSprite(); @@ -225,6 +259,7 @@ public: class SpriteFrameTest: public SpriteTestDemo { public: + CREATE_FUNC(SpriteFrameTest); virtual void onEnter(); virtual void onExit(); virtual std::string title(); @@ -233,6 +268,7 @@ public: void startIn05Secs(float dt); void flipSprites(float dt); private: + Sprite *_sprite1; Sprite *_sprite2; int _counter; @@ -241,6 +277,8 @@ private: class SpriteFrameAliasNameTest : public SpriteTestDemo { public: + CREATE_FUNC(SpriteFrameAliasNameTest); + virtual void onEnter(); virtual void onExit(); virtual std::string title(); @@ -250,6 +288,8 @@ public: class SpriteOffsetAnchorRotation: public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorRotation); + SpriteOffsetAnchorRotation(); virtual void onExit(); virtual std::string title(); @@ -258,6 +298,7 @@ public: class SpriteBatchNodeOffsetAnchorRotation: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorRotation); SpriteBatchNodeOffsetAnchorRotation(); virtual void onExit(); virtual std::string title(); @@ -266,6 +307,7 @@ public: class SpriteOffsetAnchorScale: public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorScale); SpriteOffsetAnchorScale(); virtual void onExit(); virtual std::string title(); @@ -274,6 +316,7 @@ public: class SpriteBatchNodeOffsetAnchorScale: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorScale); SpriteBatchNodeOffsetAnchorScale(); virtual void onExit(); virtual std::string title(); @@ -282,6 +325,7 @@ public: class SpriteOffsetAnchorSkew : public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorSkew); SpriteOffsetAnchorSkew(); ~SpriteOffsetAnchorSkew(); virtual std::string title(); @@ -290,6 +334,7 @@ public: class SpriteOffsetAnchorRotationalSkew : public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorRotationalSkew); SpriteOffsetAnchorRotationalSkew(); ~SpriteOffsetAnchorRotationalSkew(); virtual std::string title(); @@ -298,6 +343,7 @@ public: class SpriteBatchNodeOffsetAnchorSkew : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorSkew); SpriteBatchNodeOffsetAnchorSkew(); ~SpriteBatchNodeOffsetAnchorSkew(); virtual std::string title(); @@ -306,6 +352,7 @@ public: class SpriteOffsetAnchorRotationalSkewScale : public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorRotationalSkewScale); SpriteOffsetAnchorRotationalSkewScale(); ~SpriteOffsetAnchorRotationalSkewScale(); virtual std::string title(); @@ -314,6 +361,7 @@ public: class SpriteBatchNodeOffsetAnchorRotationalSkew : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorRotationalSkew); SpriteBatchNodeOffsetAnchorRotationalSkew(); ~SpriteBatchNodeOffsetAnchorRotationalSkew(); virtual std::string title(); @@ -322,6 +370,7 @@ public: class SpriteOffsetAnchorSkewScale : public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorSkewScale); SpriteOffsetAnchorSkewScale(); ~SpriteOffsetAnchorSkewScale(); virtual std::string title(); @@ -330,6 +379,7 @@ public: class SpriteBatchNodeOffsetAnchorSkewScale : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorSkewScale); SpriteBatchNodeOffsetAnchorSkewScale(); ~SpriteBatchNodeOffsetAnchorSkewScale(); virtual std::string title(); @@ -338,6 +388,7 @@ public: class SpriteBatchNodeOffsetAnchorRotationalSkewScale : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorRotationalSkewScale); SpriteBatchNodeOffsetAnchorRotationalSkewScale(); ~SpriteBatchNodeOffsetAnchorRotationalSkewScale(); virtual std::string title(); @@ -346,6 +397,7 @@ public: class SpriteOffsetAnchorFlip : public SpriteTestDemo { public: + CREATE_FUNC(SpriteOffsetAnchorFlip); SpriteOffsetAnchorFlip(); ~SpriteOffsetAnchorFlip(); virtual std::string title(); @@ -355,6 +407,7 @@ public: class SpriteBatchNodeOffsetAnchorFlip : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeOffsetAnchorFlip); SpriteBatchNodeOffsetAnchorFlip(); ~SpriteBatchNodeOffsetAnchorFlip(); virtual std::string title(); @@ -364,6 +417,7 @@ public: class SpriteAnimationSplit : public SpriteTestDemo { public: + CREATE_FUNC(SpriteAnimationSplit); SpriteAnimationSplit(); virtual void onExit(); virtual std::string title(); @@ -373,6 +427,8 @@ class SpriteHybrid: public SpriteTestDemo { bool _usingSpriteBatchNode; public: + CREATE_FUNC(SpriteHybrid); + SpriteHybrid(); void reparentSprite(float dt); virtual std::string title(); @@ -382,6 +438,7 @@ public: class SpriteBatchNodeChildren: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeChildren); SpriteBatchNodeChildren(); virtual void onExit(); virtual std::string title(); @@ -390,6 +447,7 @@ public: class SpriteBatchNodeChildrenZ : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeChildrenZ); SpriteBatchNodeChildrenZ(); virtual void onExit(); virtual std::string title(); @@ -398,6 +456,7 @@ public: class SpriteChildrenVisibility: public SpriteTestDemo { public: + CREATE_FUNC(SpriteChildrenVisibility); SpriteChildrenVisibility(); virtual void onExit(); virtual std::string title(); @@ -406,6 +465,7 @@ public: class SpriteChildrenVisibilityIssue665 : public SpriteTestDemo { public: + CREATE_FUNC(SpriteChildrenVisibilityIssue665); SpriteChildrenVisibilityIssue665(); ~SpriteChildrenVisibilityIssue665(); virtual std::string title(); @@ -415,6 +475,7 @@ public: class SpriteChildrenAnchorPoint: public SpriteTestDemo { public: + CREATE_FUNC(SpriteChildrenAnchorPoint); SpriteChildrenAnchorPoint(); virtual void onExit(); virtual std::string title(); @@ -423,6 +484,7 @@ public: class SpriteBatchNodeChildrenAnchorPoint: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeChildrenAnchorPoint); SpriteBatchNodeChildrenAnchorPoint(); virtual void onExit(); virtual std::string title(); @@ -431,6 +493,7 @@ public: class SpriteBatchNodeChildrenScale: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeChildrenScale); SpriteBatchNodeChildrenScale(); virtual std::string title(); }; @@ -438,6 +501,7 @@ public: class SpriteChildrenChildren: public SpriteTestDemo { public: + CREATE_FUNC(SpriteChildrenChildren); SpriteChildrenChildren(); virtual std::string title(); }; @@ -446,6 +510,7 @@ public: class SpriteBatchNodeChildrenChildren: public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeChildrenChildren); SpriteBatchNodeChildrenChildren(); virtual std::string title(); }; @@ -453,6 +518,7 @@ public: class SpriteNilTexture: public SpriteTestDemo { public: + CREATE_FUNC(SpriteNilTexture); SpriteNilTexture(); virtual std::string title(); std::string subtitle(); @@ -461,6 +527,7 @@ public: class SpriteSubclass : public SpriteTestDemo { public: + CREATE_FUNC(SpriteSubclass); SpriteSubclass(); virtual std::string title(); virtual std::string subtitle(); @@ -469,6 +536,7 @@ public: class AnimationCacheTest : public SpriteTestDemo { public: + CREATE_FUNC(AnimationCacheTest); AnimationCacheTest(); virtual std::string title(); virtual std::string subtitle(); @@ -477,6 +545,7 @@ public: class NodeSort : public SpriteTestDemo { public: + CREATE_FUNC(NodeSort); NodeSort(); virtual std::string title(); @@ -495,6 +564,7 @@ private: class SpriteBatchNodeReorderSameIndex : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorderSameIndex); SpriteBatchNodeReorderSameIndex(); virtual std::string title(); @@ -513,6 +583,7 @@ private: class SpriteBatchNodeReorderOneChild : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeReorderOneChild); SpriteBatchNodeReorderOneChild(); void reorderSprite(float dt); virtual std::string title(); @@ -524,6 +595,7 @@ private: class SpriteBatchNodeSkewNegativeScaleChildren : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeSkewNegativeScaleChildren); SpriteBatchNodeSkewNegativeScaleChildren(); ~SpriteBatchNodeSkewNegativeScaleChildren(); virtual std::string title(); @@ -533,6 +605,7 @@ public: class SpriteBatchNodeRotationalSkewNegativeScaleChildren : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchNodeRotationalSkewNegativeScaleChildren); SpriteBatchNodeRotationalSkewNegativeScaleChildren(); ~SpriteBatchNodeRotationalSkewNegativeScaleChildren(); virtual std::string title(); @@ -541,6 +614,7 @@ public: class SpriteSkewNegativeScaleChildren : public SpriteTestDemo { public: + CREATE_FUNC(SpriteSkewNegativeScaleChildren); SpriteSkewNegativeScaleChildren(); ~SpriteSkewNegativeScaleChildren(); virtual std::string title(); @@ -550,6 +624,7 @@ public: class SpriteRotationalSkewNegativeScaleChildren : public SpriteTestDemo { public: + CREATE_FUNC(SpriteRotationalSkewNegativeScaleChildren); SpriteRotationalSkewNegativeScaleChildren(); ~SpriteRotationalSkewNegativeScaleChildren(); virtual std::string title(); @@ -558,6 +633,7 @@ public: class SpriteDoubleResolution : public SpriteTestDemo { public: + CREATE_FUNC(SpriteDoubleResolution); SpriteDoubleResolution(); virtual std::string title(); virtual std::string subtitle(); @@ -566,6 +642,8 @@ public: class AnimationCacheFile : public SpriteTestDemo { public: + CREATE_FUNC(AnimationCacheFile); + AnimationCacheFile(); virtual std::string title(); virtual std::string subtitle(); @@ -574,6 +652,7 @@ public: class SpriteBatchBug1217 : public SpriteTestDemo { public: + CREATE_FUNC(SpriteBatchBug1217); SpriteBatchBug1217(); virtual std::string title(); virtual std::string subtitle(); From 0189f91480a2ae48686814ee961fc74d084f5ed3 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 13 Nov 2013 17:47:26 -0800 Subject: [PATCH 03/75] More tests working [x]: Texture2D test working OK --- .../Classes/Texture2dTest/Texture2dTest.cpp | 15 +--- .../Classes/Texture2dTest/Texture2dTest.h | 75 +++++++++++++++---- 2 files changed, 65 insertions(+), 25 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 6245237ca8..206f3f086a 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -85,12 +85,6 @@ static int sceneIdx=-1; Layer* createTextureTest(int index) { auto layer = (createFunctions[index])();; - - if (layer) - { - layer->autorelease(); - } - return layer; } @@ -145,26 +139,23 @@ TextureDemo::~TextureDemo() void TextureDemo::restartCallback(Object* sender) { - auto s = new TextureTestScene(); + auto s = TextureTestScene::create(); s->addChild(restartTextureTest()); Director::getInstance()->replaceScene(s); - s->autorelease(); } void TextureDemo::nextCallback(Object* sender) { - auto s = new TextureTestScene(); + auto s = TextureTestScene::create(); s->addChild(nextTextureTest()); Director::getInstance()->replaceScene(s); - s->autorelease(); } void TextureDemo::backCallback(Object* sender) { - auto s = new TextureTestScene(); + auto s = TextureTestScene::create(); s->addChild(backTextureTest()); Director::getInstance()->replaceScene(s); - s->autorelease(); } std::string TextureDemo::title() diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h index e590f25bef..7de47425a3 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h @@ -21,6 +21,7 @@ public: class TextureTIFF : public TextureDemo { public: + CREATE_FUNC(TextureTIFF); virtual std::string title(); virtual void onEnter(); }; @@ -28,6 +29,7 @@ public: class TexturePNG : public TextureDemo { public: + CREATE_FUNC(TexturePNG); virtual std::string title(); virtual void onEnter(); }; @@ -35,22 +37,23 @@ public: class TextureJPEG : public TextureDemo { public: + CREATE_FUNC(TextureJPEG); virtual std::string title(); - virtual void onEnter(); }; class TextureWEBP : public TextureDemo { public: + CREATE_FUNC(TextureWEBP); virtual std::string title(); - virtual void onEnter(); }; class TextureMipMap : public TextureDemo { public: + CREATE_FUNC(TextureMipMap); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -59,54 +62,55 @@ public: class TexturePVRTest : public TextureDemo { public: + CREATE_FUNC(TexturePVRTest); virtual std::string title(); - virtual void onEnter(); }; class TexturePVR2BPP : public TextureDemo { public: + CREATE_FUNC(TexturePVR2BPP); virtual std::string title(); - virtual void onEnter(); }; class TexturePVR4BPP : public TextureDemo { public: + CREATE_FUNC(TexturePVR4BPP); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRRGBA8888 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA8888); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRBGRA8888 : public TextureDemo { public: + CREATE_FUNC(TexturePVRBGRA8888); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRRGBA4444 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA4444); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRRGBA4444GZ : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA4444GZ); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -115,6 +119,7 @@ public: class TexturePVRRGBA4444CCZ : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA4444CCZ); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -123,22 +128,23 @@ public: class TexturePVRRGBA5551 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA5551); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRRGB565 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGB565); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRRGB888 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGB888); virtual std::string title(); virtual void onEnter(); }; @@ -146,30 +152,31 @@ public: class TexturePVRA8 : public TextureDemo { public: + CREATE_FUNC(TexturePVRA8); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRI8 : public TextureDemo { public: + CREATE_FUNC(TexturePVRI8); virtual std::string title(); - virtual void onEnter(); }; class TexturePVRAI88 : public TextureDemo { public: + CREATE_FUNC(TexturePVRAI88); virtual std::string title(); - virtual void onEnter(); }; class TexturePVR2BPPv3 : public TextureDemo { public: + CREATE_FUNC(TexturePVR2BPPv3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -178,6 +185,7 @@ public: class TexturePVRII2BPPv3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRII2BPPv3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -186,6 +194,7 @@ public: class TexturePVR4BPPv3 : public TextureDemo { public: + CREATE_FUNC(TexturePVR4BPPv3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -194,6 +203,7 @@ public: class TexturePVRII4BPPv3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRII4BPPv3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -202,6 +212,7 @@ public: class TexturePVRRGBA8888v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA8888v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -210,6 +221,7 @@ public: class TexturePVRBGRA8888v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRBGRA8888v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -218,6 +230,7 @@ public: class TexturePVRRGBA4444v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA4444v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -226,6 +239,7 @@ public: class TexturePVRRGBA5551v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGBA5551v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -234,6 +248,7 @@ public: class TexturePVRRGB565v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGB565v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -242,6 +257,7 @@ public: class TexturePVRRGB888v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRRGB888v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -250,6 +266,7 @@ public: class TexturePVRA8v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRA8v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -258,6 +275,7 @@ public: class TexturePVRI8v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRI8v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -266,6 +284,7 @@ public: class TexturePVRAI88v3 : public TextureDemo { public: + CREATE_FUNC(TexturePVRAI88v3); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -274,6 +293,7 @@ public: class TexturePVRBadEncoding : public TextureDemo { public: + CREATE_FUNC(TexturePVRBadEncoding); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -282,6 +302,7 @@ public: class TexturePVRMipMap : public TextureDemo { public: + CREATE_FUNC(TexturePVRMipMap); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -290,6 +311,7 @@ public: class TexturePVRMipMap2 : public TextureDemo { public: + CREATE_FUNC(TexturePVRMipMap2); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -298,6 +320,7 @@ public: class TexturePVRNonSquare : public TextureDemo { public: + CREATE_FUNC(TexturePVRNonSquare); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -306,6 +329,7 @@ public: class TexturePVRNPOT4444 : public TextureDemo { public: + CREATE_FUNC(TexturePVRNPOT4444); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -314,6 +338,7 @@ public: class TexturePVRNPOT8888 : public TextureDemo { public: + CREATE_FUNC(TexturePVRNPOT8888); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -322,6 +347,7 @@ public: class TextureAlias : public TextureDemo { public: + CREATE_FUNC(TextureAlias); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -330,6 +356,7 @@ public: class TexturePixelFormat : public TextureDemo { public: + CREATE_FUNC(TexturePixelFormat); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -338,6 +365,7 @@ public: class TextureBlend : public TextureDemo { public: + CREATE_FUNC(TextureBlend); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -346,6 +374,7 @@ public: class TextureAsync : public TextureDemo { public: + CREATE_FUNC(TextureAsync); virtual ~TextureAsync(); void loadImages(float dt); void imageLoaded(Object* pObj); @@ -359,6 +388,7 @@ private: class TextureGlRepeat : public TextureDemo { public: + CREATE_FUNC(TextureGlRepeat); virtual ~TextureGlRepeat(); virtual std::string title(); @@ -368,6 +398,7 @@ public: class TextureGlClamp : public TextureDemo { public: + CREATE_FUNC(TextureGlClamp); virtual ~TextureGlClamp(); virtual std::string title(); @@ -377,6 +408,7 @@ public: class TextureSizeTest : public TextureDemo { public: + CREATE_FUNC(TextureSizeTest); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -385,6 +417,7 @@ public: class TextureCache1 : public TextureDemo { public: + CREATE_FUNC(TextureCache1); virtual std::string title(); virtual std::string subtitle(); virtual void onEnter(); @@ -393,6 +426,7 @@ public: class TextureDrawAtPoint : public TextureDemo { public: + CREATE_FUNC(TextureDrawAtPoint); ~TextureDrawAtPoint(); virtual std::string title(); virtual std::string subtitle(); @@ -405,6 +439,7 @@ private: class TextureDrawInRect : public TextureDemo { public: + CREATE_FUNC(TextureDrawInRect); ~TextureDrawInRect(); virtual std::string title(); virtual std::string subtitle(); @@ -417,12 +452,14 @@ private: class TextureTestScene : public TestScene { public: + CREATE_FUNC(TextureTestScene); virtual void runThisTest(); }; class TextureMemoryAlloc : public TextureDemo { public: + CREATE_FUNC(TextureMemoryAlloc); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -435,6 +472,7 @@ private: class TexturePVRv3Premult : public TextureDemo { public: + CREATE_FUNC(TexturePVRv3Premult); TexturePVRv3Premult(); virtual std::string title(); @@ -447,6 +485,7 @@ public: class TextureETC1 : public TextureDemo { public: + CREATE_FUNC(TextureETC1); TextureETC1(); virtual std::string title(); @@ -457,6 +496,7 @@ public: class TextureS3TCDxt1 : public TextureDemo { public: + CREATE_FUNC(TextureS3TCDxt1); TextureS3TCDxt1(); virtual std::string title(); @@ -467,6 +507,7 @@ public: class TextureS3TCDxt3 : public TextureDemo { public: + CREATE_FUNC(TextureS3TCDxt3); TextureS3TCDxt3(); virtual std::string title(); @@ -477,6 +518,7 @@ public: class TextureS3TCDxt5 : public TextureDemo { public: + CREATE_FUNC(TextureS3TCDxt5); TextureS3TCDxt5(); virtual std::string title(); @@ -487,6 +529,7 @@ public: class TextureATITCRGB : public TextureDemo { public: + CREATE_FUNC(TextureATITCRGB); TextureATITCRGB(); virtual std::string title(); @@ -497,6 +540,7 @@ public: class TextureATITCExplicit : public TextureDemo { public: + CREATE_FUNC(TextureATITCExplicit); TextureATITCExplicit(); virtual std::string title(); @@ -507,6 +551,7 @@ public: class TextureATITCInterpolated : public TextureDemo { public: + CREATE_FUNC(TextureATITCInterpolated); TextureATITCInterpolated(); virtual std::string title(); @@ -518,6 +563,7 @@ public: class TextureConvertRGB888 : public TextureDemo { public: + CREATE_FUNC(TextureConvertRGB888); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -527,6 +573,7 @@ public: class TextureConvertRGBA8888 : public TextureDemo { public: + CREATE_FUNC(TextureConvertRGBA8888); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -536,6 +583,7 @@ public: class TextureConvertI8 : public TextureDemo { public: + CREATE_FUNC(TextureConvertI8); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); @@ -545,6 +593,7 @@ public: class TextureConvertAI88 : public TextureDemo { public: + CREATE_FUNC(TextureConvertAI88); virtual void onEnter(); virtual std::string title(); virtual std::string subtitle(); From b87684c02200cb88ccfe8408330b88c7c3f4a9b6 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 14 Nov 2013 15:37:43 -0800 Subject: [PATCH 04/75] fixes Sprite::setTexture() Sprite::setTexture(std::string&) works as expected. It sets the texture rect of the sprite --- cocos/2d/CCSprite.cpp | 277 ++++++++++++++++++++++-------------------- cocos/2d/CCSprite.h | 25 ++-- 2 files changed, 159 insertions(+), 143 deletions(-) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 60f86ff429..7fb20d95df 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -145,7 +145,74 @@ Sprite* Sprite::create() bool Sprite::init(void) { - return initWithTexture(NULL, Rect::ZERO); + return initWithTexture(NULL, Rect::ZERO ); +} + +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::initWithTexture(Texture2D *texture, const Rect& rect) +{ + return initWithTexture(texture, rect, false); +} + +bool Sprite::initWithFile(const std::string& filename) +{ + CCASSERT(filename.size()>0, "Invalid filename for sprite"); + + Texture2D *texture = Director::getInstance()->getTextureCache()->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 std::string &filename, const Rect& rect) +{ + CCASSERT(filename.size()>0, "Invalid filename"); + + Texture2D *texture = Director::getInstance()->getTextureCache()->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::initWithSpriteFrameName(const std::string& spriteFrameName) +{ + CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName"); + + SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); + return initWithSpriteFrame(frame); +} + +bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) +{ + CCASSERT(spriteFrame != NULL, ""); + + bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect()); + setSpriteFrame(spriteFrame); + + return bRet; } // designated initializer @@ -200,73 +267,6 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) } } -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 std::string& filename) -{ - CCASSERT(filename.size()>0, "Invalid filename for sprite"); - - Texture2D *texture = Director::getInstance()->getTextureCache()->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 std::string &filename, const Rect& rect) -{ - CCASSERT(filename.size()>0, "Invalid filename"); - - Texture2D *texture = Director::getInstance()->getTextureCache()->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 std::string& spriteFrameName) -{ - CCASSERT(spriteFrameName.size() > 0, "Invalid spriteFrameName"); - - SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); - return initWithSpriteFrame(frame); -} - // XXX: deprecated /* Sprite* Sprite::initWithCGImage(CGImageRef pImage) @@ -304,11 +304,76 @@ Sprite::~Sprite(void) CC_SAFE_RELEASE(_texture); } +/* + * Texture methods + */ + +/* + * 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(const std::string &filename) { Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); setTexture(texture); + + Rect rect = Rect::ZERO; + rect.size = texture->getContentSize(); + setTextureRect(rect); +} + +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 (texture == nullptr) + { + // Gets the texture by key firstly. + texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY); + + // If texture wasn't in cache, create it from RAW data. + if (texture == nullptr) + { + 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 = Director::getInstance()->getTextureCache()->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() const +{ + return _texture; } void Sprite::setTextureRect(const Rect& rect) @@ -998,20 +1063,20 @@ void Sprite::setSpriteFrame(const std::string &spriteFrameName) setSpriteFrame(spriteFrame); } -void Sprite::setSpriteFrame(SpriteFrame *pNewFrame) +void Sprite::setSpriteFrame(SpriteFrame *spriteFrame) { - _unflippedOffsetPositionFromCenter = pNewFrame->getOffset(); + _unflippedOffsetPositionFromCenter = spriteFrame->getOffset(); - Texture2D *pNewTexture = pNewFrame->getTexture(); + Texture2D *texture = spriteFrame->getTexture(); // update texture before updating texture rect - if (pNewTexture != _texture) + if (texture != _texture) { - setTexture(pNewTexture); + setTexture(texture); } // update rect - _rectRotated = pNewFrame->isRotated(); - setTextureRect(pNewFrame->getRect(), _rectRotated, pNewFrame->getOriginalSize()); + _rectRotated = spriteFrame->isRotated(); + setTextureRect(spriteFrame->getRect(), _rectRotated, spriteFrame->getOriginalSize()); } void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex) @@ -1026,7 +1091,7 @@ void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); - setDisplayFrame(frame->getSpriteFrame()); + setSpriteFrame(frame->getSpriteFrame()); } bool Sprite::isFrameDisplayed(SpriteFrame *frame) const @@ -1038,7 +1103,7 @@ bool Sprite::isFrameDisplayed(SpriteFrame *frame) const frame->getOffset().equals(_unflippedOffsetPositionFromCenter)); } -SpriteFrame* Sprite::getDisplayFrame() +SpriteFrame* Sprite::getSpriteFrame() const { return SpriteFrame::createWithTexture(_texture, CC_RECT_POINTS_TO_PIXELS(_rect), @@ -1099,62 +1164,4 @@ void Sprite::updateBlendFunc(void) } } -/* - * 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 = Director::getInstance()->getTextureCache()->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 = Director::getInstance()->getTextureCache()->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 diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index a0c70d4705..ac70a17c6d 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -194,9 +194,19 @@ public: /// @{ /// @name Texture / Frame methods - /** Sets a new texture (from a filename) to the sprite */ + /** Sets a new texture (from a filename) to the sprite. + It will call `setTextureRect()` with the texture's content size. + */ virtual void setTexture(const std::string &filename ); + /** Sets a new texture to the sprite. + The Texture's rect is not changed. + */ + virtual void setTexture(Texture2D *texture) override; + + /** returns the Texture2D object used by the sprite */ + virtual Texture2D* getTexture() const override; + /** * Updates the texture rect of the Sprite in points. * It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size. @@ -224,20 +234,21 @@ public: virtual void setSpriteFrame(const std::string &spriteFrameName); /** @deprecated Use `setSpriteFrame()` instead. */ - virtual void setDisplayFrame(SpriteFrame *newFrame) CC_DEPRECATED_ATTRIBUTE { setSpriteFrame(newFrame); } + CC_DEPRECATED_ATTRIBUTE virtual void setDisplayFrame(SpriteFrame *newFrame) { setSpriteFrame(newFrame); } /** * Returns whether or not a SpriteFrame is being displayed */ virtual bool isFrameDisplayed(SpriteFrame *pFrame) const; - /** @deprecated Use getDisplayFrame() instead */ - CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); }; - /** * Returns the current displayed frame. */ - virtual SpriteFrame* getDisplayFrame(); + virtual SpriteFrame* getSpriteFrame() const; + /** @deprecated Use `getSpriteFrame()` instead */ + CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* getDisplayFrame() const { return getSpriteFrame(); } + /** @deprecated Use `getSpriteFrame()` instead */ + CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() const { return getSpriteFrame(); }; /// @} End of frames methods @@ -367,8 +378,6 @@ public: // /// @{ /// @name Functions inherited from TextureProtocol - virtual void setTexture(Texture2D *texture) override; - virtual Texture2D* getTexture() const override; /** *@code *When this function bound into js or lua,the parameter will be changed From c52dc4ff5f0a167fccd24325b18ccbdf11f6abd1 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 14 Nov 2013 15:44:22 -0800 Subject: [PATCH 05/75] Adds love to ShaderTest2 test Improves the code in ShaderTest2 --- .../Classes/ShaderTest/ShaderTest2.cpp | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index de753d2b18..89fddc5be0 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -148,24 +148,24 @@ void ShaderSprite::initShader() { GLchar * fragSource = (GLchar*) String::createWithContentsOfFile( FileUtils::getInstance()->fullPathForFilename(_fragSourceFile).c_str())->getCString(); - auto pProgram = new GLProgram(); - pProgram->initWithVertexShaderByteArray(ccPositionTextureColor_vert, fragSource); - setShaderProgram(pProgram); - pProgram->release(); + auto program = new GLProgram(); + program->initWithVertexShaderByteArray(ccPositionTextureColor_vert, fragSource); + setShaderProgram(program); + program->release(); CHECK_GL_ERROR_DEBUG(); - getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); - getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); - getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); + program->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); + program->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); + program->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); CHECK_GL_ERROR_DEBUG(); - getShaderProgram()->link(); + program->link(); CHECK_GL_ERROR_DEBUG(); - getShaderProgram()->updateUniforms(); + program->updateUniforms(); CHECK_GL_ERROR_DEBUG(); @@ -176,14 +176,12 @@ void ShaderSprite::initShader() void ShaderSprite::draw() { - GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); - BlendFunc blend = getBlendFunc(); - GL::blendFunc(blend.src, blend.dst); - - getShaderProgram()->use(); - getShaderProgram()->setUniformsForBuiltins(); + CC_NODE_DRAW_SETUP(); + setCustomUniforms(); - + + GL::enableVertexAttribs(cocos2d::GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); + GL::blendFunc(_blendFunc.src, _blendFunc.dst); GL::bindTexture2D( getTexture()->getName()); // From dd68eb47966792e1724c666bb1e60c553dbd5f26 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 14 Nov 2013 16:21:49 -0800 Subject: [PATCH 06/75] ParticleSystem uses protected constructors --- cocos/2d/CCAtlasNode.h | 34 ++-- cocos/2d/CCDrawNode.h | 18 +-- cocos/2d/CCParticleSystem.cpp | 4 +- cocos/2d/CCParticleSystem.h | 72 +++++---- cocos/2d/CCParticleSystemQuad.cpp | 30 ++-- cocos/2d/CCParticleSystemQuad.h | 45 +++--- cocos/2d/CCSprite.h | 1 + cocos/2d/CCTransition.h | 147 +++++++++--------- .../Classes/ParticleTest/ParticleTest.cpp | 45 +++--- .../Classes/ParticleTest/ParticleTest.h | 2 +- .../PerformanceParticleTest.cpp | 4 +- 11 files changed, 197 insertions(+), 205 deletions(-) diff --git a/cocos/2d/CCAtlasNode.h b/cocos/2d/CCAtlasNode.h index 8c31496d41..b196f45a1d 100644 --- a/cocos/2d/CCAtlasNode.h +++ b/cocos/2d/CCAtlasNode.h @@ -53,22 +53,7 @@ class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol public: /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ static AtlasNode * create(const std::string& filename, long tileWidth, long tileHeight, long itemsToRender); - /** - * @js ctor - */ - AtlasNode(); - /** - * @js NA - * @lua NA - */ - virtual ~AtlasNode(); - /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ - bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender); - - /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ - bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender); - /** updates the Atlas (indexed vertex array). * Shall be overridden in subclasses */ @@ -104,15 +89,24 @@ public: */ virtual const BlendFunc& getBlendFunc() const override; -private : + +protected: + AtlasNode(); + virtual ~AtlasNode(); + + /** initializes an AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ + bool initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender); + + /** initializes an AtlasNode with a texture the width and height of each item measured in points and the quantity of items to render*/ + bool initWithTexture(Texture2D* texture, long tileWidth, long tileHeight, long itemsToRender); + void calculateMaxItems(); void updateBlendFunc(); void updateOpacityModifyRGB(); - + friend class Director; void setIgnoreContentScaleFactor(bool bIgnoreContentScaleFactor); -protected: //! chars per row long _itemsPerRow; //! chars per column @@ -136,6 +130,10 @@ protected: GLint _uniformColor; // This varible is only used for LabelAtlas FPS display. So plz don't modify its value. bool _ignoreContentScaleFactor; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode); + }; // end of base_node group diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index fe7312ade8..7636cf7326 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -46,17 +46,6 @@ class CC_DLL DrawNode : public Node public: /** creates and initialize a DrawNode node */ static DrawNode* create(); - /** - * @js ctor - */ - DrawNode(); - /** - * @js NA - * @lua NA - */ - virtual ~DrawNode(); - - virtual bool init(); /** draw a dot at a position, with a given radius and color */ void drawDot(const Point &pos, float radius, const Color4F &color); @@ -99,6 +88,10 @@ public: virtual void draw() override; protected: + DrawNode(); + virtual ~DrawNode(); + virtual bool init(); + void ensureCapacity(long count); void render(); @@ -112,6 +105,9 @@ protected: BlendFunc _blendFunc; bool _dirty; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(DrawNode); }; NS_CC_END diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index ce34d18be1..19e0fb1cd0 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -148,7 +148,7 @@ ParticleSystem * ParticleSystem::create(const std::string& plistFile) return pRet; } -ParticleSystem* ParticleSystem::createWithTotalParticles(unsigned int numberOfParticles) +ParticleSystem* ParticleSystem::createWithTotalParticles(int numberOfParticles) { ParticleSystem *pRet = new ParticleSystem(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -425,7 +425,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin return bRet; } -bool ParticleSystem::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSystem::initWithTotalParticles(int numberOfParticles) { _totalParticles = numberOfParticles; diff --git a/cocos/2d/CCParticleSystem.h b/cocos/2d/CCParticleSystem.h index 1cd30b56c8..7300c90ca9 100644 --- a/cocos/2d/CCParticleSystem.h +++ b/cocos/2d/CCParticleSystem.h @@ -170,38 +170,7 @@ public: static ParticleSystem * create(const std::string& plistFile); //! create a system with a fixed number of particles - static ParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); - /** - * @js ctor - */ - ParticleSystem(); - /** - * @js NA - * @lua NA - */ - virtual ~ParticleSystem(); - - /** initializes a ParticleSystem*/ - bool init(); - /** initializes a ParticleSystem from a plist file. - This plist files can be created manually or with Particle Designer: - http://particledesigner.71squared.com/ - @since v0.99.3 - */ - bool initWithFile(const std::string& plistFile); - - /** initializes a QuadParticleSystem from a Dictionary. - @since v0.99.3 - */ - bool initWithDictionary(Dictionary *dictionary); - - /** initializes a particle system from a NSDictionary and the path from where to load the png - @since v2.1 - */ - bool initWithDictionary(Dictionary *dictionary, const std::string& dirname); - - //! Initializes a system with a fixed number of particles - virtual bool initWithTotalParticles(unsigned int numberOfParticles); + static ParticleSystem* createWithTotalParticles(int numberOfParticles); //! Add a particle to the emitter bool addParticle(); @@ -393,10 +362,42 @@ public: * @lua NA */ virtual const BlendFunc &getBlendFunc() const override; -protected: - virtual void updateBlendFunc(); protected: + /** + * @js ctor + */ + ParticleSystem(); + /** + * @js NA + * @lua NA + */ + virtual ~ParticleSystem(); + + /** initializes a ParticleSystem*/ + bool init(); + /** initializes a ParticleSystem from a plist file. + This plist files can be created manually or with Particle Designer: + http://particledesigner.71squared.com/ + @since v0.99.3 + */ + bool initWithFile(const std::string& plistFile); + + /** initializes a QuadParticleSystem from a Dictionary. + @since v0.99.3 + */ + bool initWithDictionary(Dictionary *dictionary); + + /** initializes a particle system from a NSDictionary and the path from where to load the png + @since v2.1 + */ + bool initWithDictionary(Dictionary *dictionary, const std::string& dirname); + + //! Initializes a system with a fixed number of particles + virtual bool initWithTotalParticles(int numberOfParticles); + + virtual void updateBlendFunc(); + /** whether or not the particles are using blend additive. If enabled, the following blending function will be used. @code @@ -551,6 +552,9 @@ protected: @since v0.8 */ PositionType _positionType; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSystem); }; // end of particle_nodes group diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 36d2567809..89d287bf38 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -46,7 +46,7 @@ NS_CC_BEGIN //implementation ParticleSystemQuad // overriding the init method -bool ParticleSystemQuad::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSystemQuad::initWithTotalParticles(int numberOfParticles) { // base initialization if( ParticleSystem::initWithTotalParticles(numberOfParticles) ) @@ -111,27 +111,27 @@ ParticleSystemQuad::~ParticleSystemQuad() // implementation ParticleSystemQuad -ParticleSystemQuad * ParticleSystemQuad::create(const char *plistFile) +ParticleSystemQuad * ParticleSystemQuad::create(const std::string& filename) { - ParticleSystemQuad *pRet = new ParticleSystemQuad(); - if (pRet && pRet->initWithFile(plistFile)) + ParticleSystemQuad *ret = new ParticleSystemQuad(); + if (ret && ret->initWithFile(filename)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); - return pRet; + CC_SAFE_DELETE(ret); + return ret; } -ParticleSystemQuad * ParticleSystemQuad::createWithTotalParticles(unsigned int numberOfParticles) { - ParticleSystemQuad *pRet = new ParticleSystemQuad(); - if (pRet && pRet->initWithTotalParticles(numberOfParticles)) +ParticleSystemQuad * ParticleSystemQuad::createWithTotalParticles(int numberOfParticles) { + ParticleSystemQuad *ret = new ParticleSystemQuad(); + if (ret && ret->initWithTotalParticles(numberOfParticles)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); - return pRet; + CC_SAFE_DELETE(ret); + return ret; } diff --git a/cocos/2d/CCParticleSystemQuad.h b/cocos/2d/CCParticleSystemQuad.h index 594810cf96..5f11dd1533 100644 --- a/cocos/2d/CCParticleSystemQuad.h +++ b/cocos/2d/CCParticleSystemQuad.h @@ -57,26 +57,11 @@ public: /** creates a Particle Emitter */ static ParticleSystemQuad * create(); /** creates a Particle Emitter with a number of particles */ - static ParticleSystemQuad * createWithTotalParticles(unsigned int numberOfParticles); + static ParticleSystemQuad * createWithTotalParticles(int numberOfParticles); /** creates an initializes a ParticleSystemQuad from a plist file. This plist files can be created manually or with Particle Designer: */ - static ParticleSystemQuad * create(const char *plistFile); - /** - * @js ctor - */ - ParticleSystemQuad(); - /** - * @js NA - * @lua NA - */ - virtual ~ParticleSystemQuad(); - - /** initializes the indices for the vertices*/ - void initIndices(); - - /** initializes the texture with a rectangle measured Points */ - void initTexCoordsWithRect(const Rect& rect); + static ParticleSystemQuad * create(const std::string& filename); /** Sets a new SpriteFrame as particle. WARNING: this method is experimental. Use setTextureWithRect instead. @@ -102,7 +87,7 @@ public: * @js NA * @lua NA */ - virtual bool initWithTotalParticles(unsigned int numberOfParticles) override; + virtual bool initWithTotalParticles(int numberOfParticles) override; /** * @js NA * @lua NA @@ -134,18 +119,36 @@ public: */ virtual void setTotalParticles(int tp) override; -private: +protected: + /** + * @js ctor + */ + ParticleSystemQuad(); + /** + * @js NA + * @lua NA + */ + virtual ~ParticleSystemQuad(); + + /** initializes the indices for the vertices*/ + void initIndices(); + + /** initializes the texture with a rectangle measured Points */ + void initTexCoordsWithRect(const Rect& rect); + void setupVBOandVAO(); void setupVBO(); bool allocMemory(); - -protected: + V3F_C4B_T2F_Quad *_quads; // quads to be rendered GLushort *_indices; // indices GLuint _VAOname; GLuint _buffersVBO[2]; //0: vertex 1: indices + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSystemQuad); }; // end of particle_nodes group diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index ac70a17c6d..878ef94e51 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -196,6 +196,7 @@ public: /** Sets a new texture (from a filename) to the sprite. It will call `setTextureRect()` with the texture's content size. + TODO: The whole Sprite API needs to be reviewed. */ virtual void setTexture(const std::string &filename ); diff --git a/cocos/2d/CCTransition.h b/cocos/2d/CCTransition.h index bdcd8b58e7..74885302a6 100644 --- a/cocos/2d/CCTransition.h +++ b/cocos/2d/CCTransition.h @@ -77,18 +77,6 @@ public: /** creates a base transition with duration and incoming scene */ static TransitionScene * create(float t, Scene *scene); - /** - * @js ctor - */ - TransitionScene(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionScene(); - - /** initializes a transition with duration and incoming scene */ - bool initWithDuration(float t,Scene* scene); /** called after the transition finishes */ void finish(void); @@ -113,17 +101,23 @@ public: virtual void cleanup() override; protected: - virtual void sceneOrder(); + TransitionScene(); + virtual ~TransitionScene(); -private: + /** initializes a transition with duration and incoming scene */ + bool initWithDuration(float t,Scene* scene); + + virtual void sceneOrder(); void setNewScene(float dt); -protected: Scene * _inScene; Scene * _outScene; float _duration; bool _isInSceneOnTop; bool _isSendCleanupToScene; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionScene); }; /** @brief A Transition that supports orientation like. @@ -134,21 +128,18 @@ class CC_DLL TransitionSceneOriented : public TransitionScene public: /** creates a base transition with duration and incoming scene */ static TransitionSceneOriented * create(float t,Scene* scene, Orientation orientation); - /** - * @js ctor - */ + +protected: TransitionSceneOriented(); - /** - * @js NA - * @lua NA - */ virtual ~TransitionSceneOriented(); /** initializes a transition with duration and incoming scene */ bool initWithDuration(float t,Scene* scene,Orientation orientation); -protected: Orientation _orientation; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSceneOriented); }; /** @brief TransitionRotoZoom: @@ -159,12 +150,6 @@ class CC_DLL TransitionRotoZoom : public TransitionScene public: static TransitionRotoZoom* create(float t, Scene* scene); - TransitionRotoZoom(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionRotoZoom(); // // Overrides @@ -174,6 +159,14 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionRotoZoom(); + virtual ~TransitionRotoZoom(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionRotoZoom); + }; /** @brief TransitionJumpZoom: @@ -183,15 +176,6 @@ class CC_DLL TransitionJumpZoom : public TransitionScene { public: static TransitionJumpZoom* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionJumpZoom(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionJumpZoom(); // // Overrides @@ -201,6 +185,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionJumpZoom(); + virtual ~TransitionJumpZoom(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionJumpZoom); }; /** @brief TransitionMoveInL: @@ -210,15 +201,7 @@ class CC_DLL TransitionMoveInL : public TransitionScene, public TransitionEaseSc { public: static TransitionMoveInL* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionMoveInL(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionMoveInL(); + /** initializes the scenes */ virtual void initScenes(void); /** returns the action that will be performed */ @@ -234,6 +217,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionMoveInL(); + virtual ~TransitionMoveInL(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInL); }; /** @brief TransitionMoveInR: @@ -243,16 +233,14 @@ class CC_DLL TransitionMoveInR : public TransitionMoveInL { public: static TransitionMoveInR* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionMoveInR(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionMoveInR(); virtual void initScenes(); + +protected: + TransitionMoveInR(); + virtual ~TransitionMoveInR(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInR); }; /** @brief TransitionMoveInT: @@ -262,16 +250,14 @@ class CC_DLL TransitionMoveInT : public TransitionMoveInL { public: static TransitionMoveInT* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionMoveInT(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionMoveInT(); virtual void initScenes(); + +protected: + TransitionMoveInT(); + virtual ~TransitionMoveInT(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInT); }; /** @brief TransitionMoveInB: @@ -281,6 +267,9 @@ class CC_DLL TransitionMoveInB : public TransitionMoveInL { public: static TransitionMoveInB* create(float t, Scene* scene); + virtual void initScenes(); + +protected: /** * @js ctor */ @@ -290,7 +279,9 @@ public: * @lua NA */ virtual ~TransitionMoveInB(); - virtual void initScenes(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInB); }; /** @brief TransitionSlideInL: @@ -300,15 +291,6 @@ class CC_DLL TransitionSlideInL : public TransitionScene, public TransitionEaseS { public: static TransitionSlideInL* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSlideInL(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSlideInL(); virtual ActionInterval* easeActionWithAction(ActionInterval * action); @@ -325,9 +307,22 @@ public: * @lua NA */ virtual void onEnter() override; - + protected: + /** + * @js ctor + */ + TransitionSlideInL(); + /** + * @js NA + * @lua NA + */ + virtual ~TransitionSlideInL(); + virtual void sceneOrder() override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInL); }; /** @brief TransitionSlideInR: diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index c4e3b15bad..88fd2cebd2 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -135,9 +135,8 @@ void DemoBigFlower::onEnter() { ParticleDemo::onEnter(); - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(50); - //_emitter->autorelease(); + _emitter = ParticleSystemQuad::createWithTotalParticles(50); + _emitter->retain(); _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : use this line or remove this line and use autorelease() @@ -219,9 +218,8 @@ void DemoRotFlower::onEnter() { ParticleDemo::onEnter(); - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(300); - //_emitter->autorelease(); + _emitter = ParticleSystemQuad::createWithTotalParticles(300); + _emitter->retain(); _background->addChild(_emitter, 10); ////_emitter->release(); // win32 : Remove this line @@ -477,10 +475,8 @@ void DemoModernArt::onEnter() //FIXME: If use ParticleSystemPoint, bada 1.0 device will crash. // Crash place: ParticleSystemPoint.cpp Line 149, function: glDrawArrays(GL_POINTS, 0, _particleIdx); -// _emitter = new ParticleSystemPoint(); - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(1000); - //_emitter->autorelease(); + _emitter = ParticleSystemQuad::createWithTotalParticles(1000); + _emitter->retain(); _background->addChild(_emitter, 10); ////_emitter->release(); @@ -638,8 +634,8 @@ void RadiusMode1::onEnter() removeChild(_background, true); _background = NULL; - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(200); + _emitter = ParticleSystemQuad::createWithTotalParticles(200); + _emitter->retain(); addChild(_emitter, 10); _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); @@ -722,8 +718,8 @@ void RadiusMode2::onEnter() removeChild(_background, true); _background = NULL; - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(200); + _emitter = ParticleSystemQuad::createWithTotalParticles(200); + _emitter->retain(); addChild(_emitter, 10); _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/stars-grayscale.png")); @@ -806,8 +802,8 @@ void Issue704::onEnter() removeChild(_background, true); _background = NULL; - _emitter = new ParticleSystemQuad(); - _emitter->initWithTotalParticles(100); + _emitter = ParticleSystemQuad::createWithTotalParticles(100); + _emitter->retain(); addChild(_emitter, 10); _emitter->setTexture(Director::getInstance()->getTextureCache()->addImage("Images/fire.png")); @@ -898,11 +894,10 @@ void Issue870::onEnter() removeChild(_background, true); _background = NULL; - auto system = new ParticleSystemQuad(); - system->initWithFile("Particles/SpinningPeas.plist"); - system->setTextureWithRect(Director::getInstance()->getTextureCache()->addImage("Images/particles.png"), Rect(0,0,32,32)); - addChild(system, 10); - _emitter = system; + _emitter = ParticleSystemQuad::create("Particles/SpinningPeas.plist"); + _emitter->setTextureWithRect(Director::getInstance()->getTextureCache()->addImage("Images/particles.png"), Rect(0,0,32,32)); + addChild(_emitter, 10); + _emitter->retain(); _index = 0; schedule(schedule_selector(Issue870::updateQuads), 2.0f); @@ -939,9 +934,9 @@ void DemoParticleFromFile::onEnter() removeChild(_background, true); _background = NULL; - _emitter = new ParticleSystemQuad(); std::string filename = "Particles/" + _title + ".plist"; - _emitter->initWithFile(filename.c_str()); + _emitter = ParticleSystemQuad::create(filename); + _emitter->retain(); addChild(_emitter, 10); setEmitterPosition(); @@ -1717,8 +1712,8 @@ void ReorderParticleSystems::onEnter() for (int i = 0; i<3; i++) { - auto particleSystem = new ParticleSystemQuad(); - particleSystem->initWithTotalParticles(200); + auto particleSystem = ParticleSystemQuad::createWithTotalParticles(200); + particleSystem->retain(); particleSystem->setTexture(_batchNode->getTexture()); // duration diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h index 4c9e63047f..f5fe206faf 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h @@ -16,7 +16,7 @@ public: class ParticleDemo : public BaseTest { protected: - ParticleSystem* _emitter; + ParticleSystemQuad* _emitter; Sprite* _background; LayerColor* _color; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp index b6878a5b22..12cacb6421 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp @@ -170,7 +170,7 @@ void ParticleMainScene::step(float dt) void ParticleMainScene::createParticleSystem() { - ParticleSystem *particleSystem = NULL; + ParticleSystemQuad *particleSystem = nullptr; /* * Tests: @@ -196,7 +196,7 @@ void ParticleMainScene::createParticleSystem() // } // else { - particleSystem = new ParticleSystemQuad(); + particleSystem = ParticleSystemQuad::create(); } switch( subtestNumber) From 17a6575bd3fbf9e12f08803e70a013fd72e9407c Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 14 Nov 2013 16:33:43 -0800 Subject: [PATCH 07/75] more protected constructors Adds protected constructors for: * ClippingNode * ParallaxNode * RenderTexture * TMXTiledMap --- cocos/2d/CCClippingNode.h | 42 ++++++++++--------- cocos/2d/CCMotionStreak.h | 34 ++++++++------- cocos/2d/CCParallaxNode.h | 27 ++++++------ cocos/2d/CCProgressTimer.h | 28 +++++++------ cocos/2d/CCRenderTexture.h | 38 +++++++++-------- cocos/2d/CCTMXTiledMap.h | 39 +++++++++-------- .../RenderTextureTest/RenderTextureTest.cpp | 12 +++--- .../RenderTextureTest/RenderTextureTest.h | 2 +- 8 files changed, 121 insertions(+), 101 deletions(-) diff --git a/cocos/2d/CCClippingNode.h b/cocos/2d/CCClippingNode.h index ca2a17b8d7..7c18e99e01 100644 --- a/cocos/2d/CCClippingNode.h +++ b/cocos/2d/CCClippingNode.h @@ -49,21 +49,7 @@ public: The stencil node will be retained. */ static ClippingNode* create(Node *pStencil); - /** - * @js NA - * @lua NA - */ - virtual ~ClippingNode(); - - /** Initializes a clipping node without a stencil. - */ - virtual bool init(); - - /** Initializes a clipping node with an other node as its stencil. - The stencil node will be retained, and its parent will be set to this clipping node. - */ - virtual bool init(Node *pStencil); - + /** The Node to use as a stencil to do the clipping. The stencil node will be retained. This default to nil. @@ -109,18 +95,34 @@ public: virtual void onExit() override; virtual void visit() override; -private: +protected: + ClippingNode(); + + /** + * @js NA + * @lua NA + */ + virtual ~ClippingNode(); + + /** Initializes a clipping node without a stencil. + */ + virtual bool init(); + + /** Initializes a clipping node with an other node as its stencil. + The stencil node will be retained, and its parent will be set to this clipping node. + */ + virtual bool init(Node *pStencil); + /**draw fullscreen quad to clear stencil bits */ void drawFullScreenQuadClearStencil(); -protected: - ClippingNode(); - -protected: Node* _stencil; GLfloat _alphaThreshold; bool _inverted; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode); }; NS_CC_END diff --git a/cocos/2d/CCMotionStreak.h b/cocos/2d/CCMotionStreak.h index c0fc986c73..ec454b0abc 100644 --- a/cocos/2d/CCMotionStreak.h +++ b/cocos/2d/CCMotionStreak.h @@ -53,20 +53,6 @@ public: static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, const char* path); /** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */ static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); - /** - * @js ctor - */ - MotionStreak(); - /** - * @js NA - * @lua NA - */ - virtual ~MotionStreak(); - - /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const char* path); - /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ - bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); /** color used for the tint */ void tintWithColor(const Color3B& colors); @@ -114,9 +100,24 @@ public: virtual bool isOpacityModifyRGB() const override; protected: + /** + * @js ctor + */ + MotionStreak(); + /** + * @js NA + * @lua NA + */ + virtual ~MotionStreak(); + + /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const char* path); + /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ + bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); + bool _fastMode; bool _startingPositionInitialized; -private: + /** texture used for the motion streak */ Texture2D* _texture; BlendFunc _blendFunc; @@ -138,6 +139,9 @@ private: Vertex2F* _vertices; GLubyte* _colorPointer; Tex2F* _texCoords; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MotionStreak); }; // end of misc_nodes group diff --git a/cocos/2d/CCParallaxNode.h b/cocos/2d/CCParallaxNode.h index 36c3a192a9..e7770d7282 100644 --- a/cocos/2d/CCParallaxNode.h +++ b/cocos/2d/CCParallaxNode.h @@ -48,18 +48,6 @@ class CC_DLL ParallaxNode : public Node public: // Create a Parallax node static ParallaxNode * create(); - - /** Adds a child to the container with a z-order, a parallax ratio and a position offset - It returns self, so you can chain several addChilds. - @since v0.8 - * @js ctor - */ - ParallaxNode(); - /** - * @js NA - * @lua NA - */ - virtual ~ParallaxNode(); // prevents compiler warning: "Included function hides overloaded virtual functions" using Node::addChild; @@ -81,10 +69,25 @@ public: virtual void visit(void) override; protected: + /** Adds a child to the container with a z-order, a parallax ratio and a position offset + It returns self, so you can chain several addChilds. + @since v0.8 + * @js ctor + */ + ParallaxNode(); + /** + * @js NA + * @lua NA + */ + virtual ~ParallaxNode(); + Point absolutePosition(); Point _lastPosition; struct _ccArray* _parallaxArray; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParallaxNode); }; // end of tilemap_parallax_nodes group diff --git a/cocos/2d/CCProgressTimer.h b/cocos/2d/CCProgressTimer.h index e09e34be0f..04c4e55246 100644 --- a/cocos/2d/CCProgressTimer.h +++ b/cocos/2d/CCProgressTimer.h @@ -62,18 +62,6 @@ public: /** Creates a progress timer with the sprite as the shape the timer goes through */ static ProgressTimer* create(Sprite* sp); - /** - * @js ctor - */ - ProgressTimer(); - /** - * @js NA - * @lua NA - */ - virtual ~ProgressTimer(); - - /** Initializes a progress timer with the sprite as the shape the timer goes through */ - bool initWithSprite(Sprite* sp); /** Change the percentage to change progress. */ inline Type getType() const { return _type; } @@ -129,6 +117,19 @@ public: virtual void setOpacity(GLubyte opacity) override; protected: + /** + * @js ctor + */ + ProgressTimer(); + /** + * @js NA + * @lua NA + */ + virtual ~ProgressTimer(); + + /** Initializes a progress timer with the sprite as the shape the timer goes through */ + bool initWithSprite(Sprite* sp); + Tex2F textureCoordFromAlphaPoint(Point alpha); Vertex2F vertexFromAlphaPoint(Point alpha); void updateProgress(void); @@ -146,6 +147,9 @@ protected: V2F_C4B_T2F *_vertexData; bool _reverseDirection; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ProgressTimer); }; // end of misc_nodes group diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 5318e83fdf..04d30dd4dc 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -58,21 +58,6 @@ public: /** creates a RenderTexture object with width and height in Points, pixel format is RGBA8888 */ static RenderTexture * create(int w, int h); - /** - * @js ctor - */ - RenderTexture(); - /** - * @js NA - * @lua NA - */ - virtual ~RenderTexture(); - - /** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ - bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat); - - /** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/ - bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat); /** starts grabbing */ void begin(); @@ -167,10 +152,25 @@ public: virtual void visit() override; virtual void draw() override; -private: +protected: + /** + * @js ctor + */ + RenderTexture(); + /** + * @js NA + * @lua NA + */ + virtual ~RenderTexture(); + + /** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ + bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat); + + /** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/ + bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat); + void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue, GLbitfield flags); -protected: GLuint _FBO; GLuint _depthRenderBufffer; GLint _oldFBO; @@ -192,6 +192,10 @@ protected: - [[renderTexture sprite] setBlendFunc:(BlendFunc){GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; */ Sprite* _sprite; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(RenderTexture); + }; // end of textures group diff --git a/cocos/2d/CCTMXTiledMap.h b/cocos/2d/CCTMXTiledMap.h index f870938174..7148711e56 100644 --- a/cocos/2d/CCTMXTiledMap.h +++ b/cocos/2d/CCTMXTiledMap.h @@ -109,28 +109,12 @@ object->getProperty(name_of_the_property); class CC_DLL TMXTiledMap : public Node { public: - /** - * @js ctor - */ - TMXTiledMap(); - /** - * @js NA - * @lua NA - */ - virtual ~TMXTiledMap(); - /** creates a TMX Tiled Map with a TMX file.*/ static TMXTiledMap* create(const std::string& tmxFile); /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath); - /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const std::string& tmxFile); - - /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const std::string& tmxString, const std::string& resourcePath); - /** return the TMXLayer for the specific layer */ TMXLayer* getLayer(const std::string& layerName) const; /** @@ -187,11 +171,27 @@ public: _properties = properties; }; -private: +protected: + /** + * @js ctor + */ + TMXTiledMap(); + /** + * @js NA + * @lua NA + */ + virtual ~TMXTiledMap(); + + /** initializes a TMX Tiled Map with a TMX file */ + bool initWithTMXFile(const std::string& tmxFile); + + /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ + bool initWithXML(const std::string& tmxString, const std::string& resourcePath); + TMXLayer * parseLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo); TMXTilesetInfo * tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo); void buildWithMapInfo(TMXMapInfo* mapInfo); -protected: + /** the map's size property measured in tiles */ Size _mapSize; /** the tiles's size property measured in pixels */ @@ -206,6 +206,9 @@ protected: //! tile properties Dictionary* _tileProperties; +private: + CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap); + }; // end of tilemap_parallax_nodes group diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index d305c0382b..ff4edc2b0a 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -568,7 +568,7 @@ string RenderTextureTargetNode::subtitle() // SpriteRenderTextureBug -SpriteRenderTextureBug::SimpleSprite::SimpleSprite() : rt(NULL) {} +SpriteRenderTextureBug::SimpleSprite::SimpleSprite() : _rt(nullptr) {} SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::create(const char* filename, const Rect &rect) { @@ -587,14 +587,14 @@ SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::crea void SpriteRenderTextureBug::SimpleSprite::draw() { - if (rt == NULL) + if (_rt == nullptr) { auto s = Director::getInstance()->getWinSize(); - rt = new RenderTexture(); - rt->initWithWidthAndHeight(s.width, s.height, Texture2D::PixelFormat::RGBA8888); + _rt = RenderTexture::create(s.width, s.height, Texture2D::PixelFormat::RGBA8888); + _rt->retain(); } - rt->beginWithClear(0.0f, 0.0f, 0.0f, 1.0f); - rt->end(); + _rt->beginWithClear(0.0f, 0.0f, 0.0f, 1.0f); + _rt->end(); CC_NODE_DRAW_SETUP(); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h index cedf516f3f..47fde11c59 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h @@ -115,7 +115,7 @@ public: public: - RenderTexture *rt; + RenderTexture *_rt; }; public: From a583ad461f11c50723a17515421e092abc9f270a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 14 Nov 2013 17:19:16 -0800 Subject: [PATCH 08/75] CCControlButton has protected constructor --- cocos/2d/CCAnimation.cpp | 2 +- cocos/2d/CCAnimation.h | 4 +- cocos/2d/CCLabelBMFont.cpp | 8 ++-- cocos/2d/CCLabelBMFont.h | 4 +- cocos/2d/CCParticleBatchNode.cpp | 8 ++-- cocos/2d/CCParticleBatchNode.h | 8 ++-- cocos/2d/CCRenderTexture.cpp | 6 +-- cocos/2d/CCRenderTexture.h | 4 +- cocos/2d/platform/CCImage.h | 6 +-- cocos/2d/platform/CCImageCommon_cpp.h | 26 +++++------- cocos/2d/platform/ios/CCImage.mm | 4 +- .../CCControlExtension/CCControlButton.cpp | 24 +++++------ .../GUI/CCControlExtension/CCControlButton.h | 40 ++++++++++--------- 13 files changed, 70 insertions(+), 74 deletions(-) diff --git a/cocos/2d/CCAnimation.cpp b/cocos/2d/CCAnimation.cpp index ca1c949882..fad60c6533 100644 --- a/cocos/2d/CCAnimation.cpp +++ b/cocos/2d/CCAnimation.cpp @@ -175,7 +175,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame) _totalDelayUnits++; } -void Animation::addSpriteFrameWithFile(const char *filename) +void Animation::addSpriteFrameWithFile(const std::string& filename) { Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Rect rect = Rect::ZERO; diff --git a/cocos/2d/CCAnimation.h b/cocos/2d/CCAnimation.h index cc38ca6d84..13cf3b1fdc 100644 --- a/cocos/2d/CCAnimation.h +++ b/cocos/2d/CCAnimation.h @@ -173,11 +173,11 @@ public: The frame will be added with one "delay unit". Added to facilitate the migration from v0.8 to v0.9. */ - void addSpriteFrameWithFile(const char *filename); + void addSpriteFrameWithFile(const std::string& filename); /** @deprecated. Use addSpriteFrameWithFile() instead */ - CC_DEPRECATED_ATTRIBUTE void addSpriteFrameWithFileName(const char *filename){ addSpriteFrameWithFile(filename);} + CC_DEPRECATED_ATTRIBUTE void addSpriteFrameWithFileName(const std::string& filename){ addSpriteFrameWithFile(filename);} /** Adds a frame with a texture and a rect. Internally it will create a SpriteFrame and it will add it. The frame will be added with one "delay unit". diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index a6c416eb50..88fb154770 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -1197,9 +1197,9 @@ float LabelBMFont::getLetterPosXRight( Sprite* sp ) } // LabelBMFont - FntFile -void LabelBMFont::setFntFile(const char* fntFile) +void LabelBMFont::setFntFile(const std::string& fntFile) { - if (fntFile != NULL && strcmp(fntFile, _fntFile.c_str()) != 0 ) + if (_fntFile.compare(fntFile) != 0) { CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile); @@ -1216,9 +1216,9 @@ void LabelBMFont::setFntFile(const char* fntFile) } } -const char* LabelBMFont::getFntFile() +const std::string& LabelBMFont::getFntFile() const { - return _fntFile.c_str(); + return _fntFile; } diff --git a/cocos/2d/CCLabelBMFont.h b/cocos/2d/CCLabelBMFont.h index a825d28ed6..41bd2c46bc 100644 --- a/cocos/2d/CCLabelBMFont.h +++ b/cocos/2d/CCLabelBMFont.h @@ -258,8 +258,8 @@ public: virtual bool isCascadeColorEnabled() const; virtual void setCascadeColorEnabled(bool cascadeColorEnabled); - void setFntFile(const char* fntFile); - const char* getFntFile(); + void setFntFile(const std::string& fntFile); + const std::string& getFntFile() const; #if CC_LABELBMFONT_DEBUG_DRAW virtual void draw(); #endif // CC_LABELBMFONT_DEBUG_DRAW diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index cd473bf097..0d1eccae48 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -59,7 +59,7 @@ ParticleBatchNode::~ParticleBatchNode() * creation with Texture2D */ -ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D *tex, unsigned int capacity/* = kParticleDefaultCapacity*/) +ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D *tex, int capacity/* = kParticleDefaultCapacity*/) { ParticleBatchNode * p = new ParticleBatchNode(); if( p && p->initWithTexture(tex, capacity)) @@ -75,7 +75,7 @@ ParticleBatchNode* ParticleBatchNode::createWithTexture(Texture2D *tex, unsigned * creation with File Image */ -ParticleBatchNode* ParticleBatchNode::create(const char* imageFile, unsigned int capacity/* = kParticleDefaultCapacity*/) +ParticleBatchNode* ParticleBatchNode::create(const std::string& imageFile, int capacity/* = kParticleDefaultCapacity*/) { ParticleBatchNode * p = new ParticleBatchNode(); if( p && p->initWithFile(imageFile, capacity)) @@ -90,7 +90,7 @@ ParticleBatchNode* ParticleBatchNode::create(const char* imageFile, unsigned int /* * init with Texture2D */ -bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity) +bool ParticleBatchNode::initWithTexture(Texture2D *tex, int capacity) { _textureAtlas = new TextureAtlas(); _textureAtlas->initWithTexture(tex, capacity); @@ -109,7 +109,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity) /* * init with FileImage */ -bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity) +bool ParticleBatchNode::initWithFile(const std::string& fileImage, int capacity) { Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage); return initWithTexture(tex, capacity); diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index 9b5808be45..937c348500 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -68,10 +68,10 @@ class CC_DLL ParticleBatchNode : public Node, public TextureProtocol { public: /** initializes the particle system with Texture2D, a capacity of particles, which particle system to use */ - static ParticleBatchNode* createWithTexture(Texture2D *tex, unsigned int capacity = kParticleDefaultCapacity); + static ParticleBatchNode* createWithTexture(Texture2D *tex, int capacity = kParticleDefaultCapacity); /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the Texture2D class), a capacity of particles */ - static ParticleBatchNode* create(const char* fileImage, unsigned int capacity = kParticleDefaultCapacity); + static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity); /** * @js ctor */ @@ -83,10 +83,10 @@ public: virtual ~ParticleBatchNode(); /** initializes the particle system with Texture2D, a capacity of particles */ - bool initWithTexture(Texture2D *tex, unsigned int capacity); + bool initWithTexture(Texture2D *tex, int capacity); /** initializes the particle system with the name of a file on disk (for a list of supported formats look at the Texture2D class), a capacity of particles */ - bool initWithFile(const char* fileImage, unsigned int capacity); + bool initWithFile(const std::string& fileImage, int capacity); /** Inserts a child into the ParticleBatchNode */ void insertChild(ParticleSystem* system, int index); diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 8fa56c282d..a35a564f85 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -543,20 +543,20 @@ void RenderTexture::draw() } } -bool RenderTexture::saveToFile(const char *szFilePath) +bool RenderTexture::saveToFile(const std::string& filename) { bool ret = false; Image *image = newImage(true); if (image) { - ret = image->saveToFile(szFilePath); + ret = image->saveToFile(filename); } CC_SAFE_DELETE(image); return ret; } -bool RenderTexture::saveToFile(const char *fileName, Image::Format format) +bool RenderTexture::saveToFile(const std::string& fileName, Image::Format format) { bool bRet = false; CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG, diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 04d30dd4dc..90b2ba1784 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -99,12 +99,12 @@ public: /** saves the texture into a file using JPEG format. The file will be saved in the Documents folder. Returns true if the operation is successful. */ - bool saveToFile(const char *szFilePath); + bool saveToFile(const std::string& filename); /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. */ - bool saveToFile(const char *name, Image::Format format); + bool saveToFile(const std::string& filename, Image::Format format); /** Listen "come to background" message, and save render texture. It only has effect on Android. diff --git a/cocos/2d/platform/CCImage.h b/cocos/2d/platform/CCImage.h index 1f2e04ced7..781689f238 100644 --- a/cocos/2d/platform/CCImage.h +++ b/cocos/2d/platform/CCImage.h @@ -193,7 +193,7 @@ public: @param filePath the file's absolute path, including file suffix. @param isToRGB whether the image is saved as RGB format. */ - bool saveToFile(const char *filePath, bool isToRGB = true); + bool saveToFile(const std::string &filename, bool isToRGB = true); protected: bool initWithJpgData(const unsigned char * data, int dataLen); @@ -207,8 +207,8 @@ protected: bool initWithS3TCData(const unsigned char * data, int dataLen); bool initWithATITCData(const unsigned char *data, int dataLen); - bool saveImageToPNG(const char *filePath, bool isToRGB = true); - bool saveImageToJPG(const char *filePath); + bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); + bool saveImageToJPG(const std::string& filePath); private: /** diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index 09b73ea421..eca8c685cc 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -1784,7 +1784,7 @@ bool Image::initWithRawData(const unsigned char * data, long dataLen, long width #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) -bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB) +bool Image::saveToFile(const std::string& filename, bool bIsToRGB) { //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888)) @@ -1801,24 +1801,22 @@ bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB) do { - CC_BREAK_IF(NULL == pszFilePath); - std::string strFilePath(pszFilePath); - CC_BREAK_IF(strFilePath.size() <= 4); + CC_BREAK_IF(filename.size() <= 4); - std::string strLowerCasePath(strFilePath); + std::string strLowerCasePath(filename); for (unsigned int i = 0; i < strLowerCasePath.length(); ++i) { - strLowerCasePath[i] = tolower(strFilePath[i]); + strLowerCasePath[i] = tolower(filename[i]); } if (std::string::npos != strLowerCasePath.find(".png")) { - CC_BREAK_IF(!saveImageToPNG(pszFilePath, bIsToRGB)); + CC_BREAK_IF(!saveImageToPNG(filename, bIsToRGB)); } else if (std::string::npos != strLowerCasePath.find(".jpg")) { - CC_BREAK_IF(!saveImageToJPG(pszFilePath)); + CC_BREAK_IF(!saveImageToJPG(filename)); } else { @@ -1833,20 +1831,18 @@ bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB) } #endif -bool Image::saveImageToPNG(const char * filePath, bool isToRGB) +bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) { bool bRet = false; do { - CC_BREAK_IF(NULL == filePath); - FILE *fp; png_structp png_ptr; png_infop info_ptr; png_colorp palette; png_bytep *row_pointers; - fp = fopen(filePath, "wb"); + fp = fopen(filePath.c_str(), "wb"); CC_BREAK_IF(NULL == fp); png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); @@ -1973,13 +1969,11 @@ bool Image::saveImageToPNG(const char * filePath, bool isToRGB) } while (0); return bRet; } -bool Image::saveImageToJPG(const char * filePath) +bool Image::saveImageToJPG(const std::string& filePath) { bool bRet = false; do { - CC_BREAK_IF(NULL == filePath); - struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE * outfile; /* target file */ @@ -1990,7 +1984,7 @@ bool Image::saveImageToJPG(const char * filePath) /* Now we can initialize the JPEG compression object. */ jpeg_create_compress(&cinfo); - CC_BREAK_IF((outfile = fopen(filePath, "wb")) == NULL); + CC_BREAK_IF((outfile = fopen(filePath.c_str(), "wb")) == NULL); jpeg_stdio_dest(&cinfo, outfile); diff --git a/cocos/2d/platform/ios/CCImage.mm b/cocos/2d/platform/ios/CCImage.mm index 556a4abcba..ff902b6bb5 100644 --- a/cocos/2d/platform/ios/CCImage.mm +++ b/cocos/2d/platform/ios/CCImage.mm @@ -380,11 +380,11 @@ bool Image::initWithStringShadowStroke( return true; } -bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB) +bool Image::saveToFile(const std::string& filename, bool bIsToRGB) { bool saveToPNG = false; bool needToCopyPixels = false; - std::string filePath(pszFilePath); + if (std::string::npos != filePath.find(".png")) { saveToPNG = true; diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index e747dfe24c..db18da4cdd 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -388,7 +388,7 @@ void ControlButton::setTitleLabelForState(Node* titleLabel, State state) } } -void ControlButton::setTitleTTFForState(const char * fntFile, State state) +void ControlButton::setTitleTTFForState(const std::string& fntFile, State state) { String * title = this->getTitleForState(state); if (!title) @@ -398,18 +398,17 @@ void ControlButton::setTitleTTFForState(const char * fntFile, State state) this->setTitleLabelForState(LabelTTF::create(title->getCString(), fntFile, 12), state); } -const char * ControlButton::getTitleTTFForState(State state) +const std::string& ControlButton::getTitleTTFForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); LabelTTF* labelTTF = dynamic_cast(label); if(labelTTF != 0) { - return labelTTF->getFontName().c_str(); - } - else - { - return ""; + return labelTTF->getFontName(); } + + static std::string ret(""); + return ret; } void ControlButton::setTitleTTFSizeForState(float size, State state) @@ -439,7 +438,7 @@ float ControlButton::getTitleTTFSizeForState(State state) } } -void ControlButton::setTitleBMFontForState(const char * fntFile, State state) +void ControlButton::setTitleBMFontForState(const std::string& fntFile, State state) { String * title = this->getTitleForState(state); if (!title) @@ -449,7 +448,7 @@ void ControlButton::setTitleBMFontForState(const char * fntFile, State state) this->setTitleLabelForState(LabelBMFont::create(title->getCString(), fntFile), state); } -const char * ControlButton::getTitleBMFontForState(State state) +const std::string& ControlButton::getTitleBMFontForState(State state) { LabelProtocol* label = dynamic_cast(this->getTitleLabelForState(state)); LabelBMFont* labelBMFont = dynamic_cast(label); @@ -457,10 +456,9 @@ const char * ControlButton::getTitleBMFontForState(State state) { return labelBMFont->getFntFile(); } - else - { - return ""; - } + + static std::string ret(""); + return ret; } diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 5a30c64f4c..1da0d5c74d 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -57,20 +57,6 @@ public: static ControlButton* create(Scale9Sprite* sprite); static ControlButton* create(Node* label, Scale9Sprite* backgroundSprite); static ControlButton* create(std::string title, const char * fontName, float fontSize); - /** - * @js ctor - */ - ControlButton(); - /** - * @js NA - * @lua NA - */ - virtual ~ControlButton(); - - virtual bool init(); - virtual bool initWithLabelAndBackgroundSprite(Node* label, Scale9Sprite* backgroundSprite); - virtual bool initWithBackgroundSprite(Scale9Sprite* sprite); - virtual bool initWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); virtual void needsLayout(void); @@ -140,8 +126,8 @@ public: */ virtual void setTitleLabelForState(Node* label, State state); - virtual void setTitleTTFForState(const char * fntFile, State state); - virtual const char * getTitleTTFForState(State state); + virtual void setTitleTTFForState(const std::string& fntFile, State state); + virtual const std::string& getTitleTTFForState(State state); virtual void setTitleTTFSizeForState(float size, State state); virtual float getTitleTTFSizeForState(State state); @@ -152,8 +138,8 @@ public: * @param state The state that uses the specified fntFile. The values are described * in "CCControlState". */ - virtual void setTitleBMFontForState(const char * fntFile, State state); - virtual const char * getTitleBMFontForState(State state); + virtual void setTitleBMFontForState(const std::string& fntFile, State state); + virtual const std::string& getTitleBMFontForState(State state); /** * Returns the background sprite used for a state. @@ -209,6 +195,21 @@ public: void setAdjustBackgroundImage(bool adjustBackgroundImage); protected: + /** + * @js ctor + */ + ControlButton(); + /** + * @js NA + * @lua NA + */ + virtual ~ControlButton(); + + virtual bool init(); + virtual bool initWithLabelAndBackgroundSprite(Node* label, Scale9Sprite* backgroundSprite); + virtual bool initWithBackgroundSprite(Scale9Sprite* sprite); + virtual bool initWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); + bool _isPushed; bool _parentInited; bool _doesAdjustBackgroundImage; @@ -246,6 +247,9 @@ protected: CC_SYNTHESIZE_READONLY(int, _marginV, VerticalMargin); /* Define the button margin for Left/Right edge */ CC_SYNTHESIZE_READONLY(int, _marginH, HorizontalOrigin); + +protected: + CC_DISALLOW_COPY_AND_ASSIGN(ControlButton); }; // end of GUI group From 208d25bdff9179f18ee62de730942d795c109233 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 15 Nov 2013 12:04:47 -0800 Subject: [PATCH 09/75] ControlSwitch compies Uses procted constructor --- cocos/2d/CCActionTween.cpp | 4 +- cocos/2d/CCActionTween.h | 6 +- cocos/2d/platform/ios/CCImage.mm | 4 +- .../CCControlExtension/CCControlSwitch.cpp | 92 ++++++++++++------- 4 files changed, 67 insertions(+), 39 deletions(-) diff --git a/cocos/2d/CCActionTween.cpp b/cocos/2d/CCActionTween.cpp index bd615eb599..67a4f3ce38 100644 --- a/cocos/2d/CCActionTween.cpp +++ b/cocos/2d/CCActionTween.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. NS_CC_BEGIN -ActionTween* ActionTween::create(float aDuration, const char* key, float from, float to) +ActionTween* ActionTween::create(float aDuration, const std::string& key, float from, float to) { ActionTween* pRet = new ActionTween(); if (pRet && pRet->initWithDuration(aDuration, key, from, to)) @@ -41,7 +41,7 @@ ActionTween* ActionTween::create(float aDuration, const char* key, float from, f return pRet; } -bool ActionTween::initWithDuration(float aDuration, const char* key, float from, float to) +bool ActionTween::initWithDuration(float aDuration, const std::string& key, float from, float to) { if (ActionInterval::initWithDuration(aDuration)) { diff --git a/cocos/2d/CCActionTween.h b/cocos/2d/CCActionTween.h index 2ed389d810..b5c1553f31 100644 --- a/cocos/2d/CCActionTween.h +++ b/cocos/2d/CCActionTween.h @@ -42,7 +42,7 @@ public: * @lua NA */ virtual ~ActionTweenDelegate() {} - virtual void updateTweenAction(float value, const char* key) = 0; + virtual void updateTweenAction(float value, const std::string& key) = 0; }; /** ActionTween @@ -69,9 +69,9 @@ class CC_DLL ActionTween : public ActionInterval { public: /** creates an initializes the action with the property name (key), and the from and to parameters. */ - static ActionTween* create(float duration, const char* key, float from, float to); + static ActionTween* create(float duration, const std::string& key, float from, float to); /** initializes the action with the property name (key), and the from and to parameters. */ - bool initWithDuration(float duration, const char* key, float from, float to); + bool initWithDuration(float duration, const std::string& key, float from, float to); // Overrides void startWithTarget(Node *target) override; diff --git a/cocos/2d/platform/ios/CCImage.mm b/cocos/2d/platform/ios/CCImage.mm index ff902b6bb5..2d65540a71 100644 --- a/cocos/2d/platform/ios/CCImage.mm +++ b/cocos/2d/platform/ios/CCImage.mm @@ -385,7 +385,7 @@ bool Image::saveToFile(const std::string& filename, bool bIsToRGB) bool saveToPNG = false; bool needToCopyPixels = false; - if (std::string::npos != filePath.find(".png")) + if (std::string::npos != filename.find(".png")) { saveToPNG = true; } @@ -453,7 +453,7 @@ bool Image::saveToFile(const std::string& filename, bool bIsToRGB) data = UIImageJPEGRepresentation(image, 1.0f); } - [data writeToFile:[NSString stringWithUTF8String:pszFilePath] atomically:YES]; + [data writeToFile:[NSString stringWithUTF8String:filename.c_str()] atomically:YES]; [image release]; diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index fe67a3f905..8a7d046593 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -34,32 +34,20 @@ NS_CC_EXT_BEGIN class ControlSwitchSprite : public Sprite, public ActionTweenDelegate { public: + /** creates an autorelease instance of ControlSwitchSprite */ + static ControlSwitchSprite* createWithMaskSprite( + Sprite *maskSprite, + Sprite *onSprite, + Sprite *offSprite, + Sprite *thumbSprite, + LabelTTF* onLabel, + LabelTTF* offLabel); + /** * @js NA * @lua NA */ - ControlSwitchSprite(); - /** - * @js NA - * @lua NA - */ - virtual ~ControlSwitchSprite(); - /** - * @js NA - * @lua NA - */ - bool initWithMaskSprite( - Sprite *maskSprite, - Sprite *onSprite, - Sprite *offSprite, - Sprite *thumbSprite, - LabelTTF* onLabel, - LabelTTF* offLabel); - /** - * @js NA - * @lua NA - */ - void draw(); + void draw() override; /** * @js NA * @lua NA @@ -89,7 +77,8 @@ public: * @js NA * @lua NA */ - virtual void updateTweenAction(float value, const char* key); + virtual void updateTweenAction(float value, const std::string& key) override; + /** Contains the position (in x-axis) of the slider inside the receiver. */ float _sliderXPosition; CC_SYNTHESIZE(float, _onPosition, OnPosition) @@ -104,8 +93,47 @@ public: CC_SYNTHESIZE_RETAIN(Sprite*, _thumbSprite, ThumbSprite) CC_SYNTHESIZE_RETAIN(LabelTTF*, _onLabel, OnLabel) CC_SYNTHESIZE_RETAIN(LabelTTF*, _offLabel, OffLabel) + +protected: + /** + * @js NA + * @lua NA + */ + ControlSwitchSprite(); + /** + * @js NA + * @lua NA + */ + virtual ~ControlSwitchSprite(); + /** + * @js NA + * @lua NA + */ + bool initWithMaskSprite( + Sprite *maskSprite, + Sprite *onSprite, + Sprite *offSprite, + Sprite *thumbSprite, + LabelTTF* onLabel, + LabelTTF* offLabel); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ControlSwitchSprite); }; +ControlSwitchSprite* ControlSwitchSprite::createWithMaskSprite(Sprite *maskSprite, + Sprite *onSprite, + Sprite *offSprite, + Sprite *thumbSprite, + LabelTTF* onLabel, + LabelTTF* offLabel) +{ + auto ret = new ControlSwitchSprite(); + ret->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel); + ret->autorelease(); + return ret; +} + ControlSwitchSprite::ControlSwitchSprite() : _sliderXPosition(0.0f) , _onPosition(0.0f) @@ -187,9 +215,9 @@ bool ControlSwitchSprite::initWithMaskSprite( return false; } -void ControlSwitchSprite::updateTweenAction(float value, const char* key) +void ControlSwitchSprite::updateTweenAction(float value, const std::string& key) { - CCLOG("key = %s, value = %f", key, value); + CCLOG("key = %s, value = %f", key.c_str(), value); setSliderXPosition(value); } @@ -348,13 +376,13 @@ bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sp _on = true; - _switchSprite = new ControlSwitchSprite(); - _switchSprite->initWithMaskSprite(maskSprite, - onSprite, - offSprite, - thumbSprite, - onLabel, - offLabel); + _switchSprite = ControlSwitchSprite::createWithMaskSprite(maskSprite, + onSprite, + offSprite, + thumbSprite, + onLabel, + offLabel); + _switchSprite->retain(); _switchSprite->setPosition(Point(_switchSprite->getContentSize().width / 2, _switchSprite->getContentSize().height / 2)); addChild(_switchSprite); From 7c2ed2743ce9389990342a15c4e3d25a8aa91d73 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 15 Nov 2013 13:14:12 -0800 Subject: [PATCH 10/75] Menu + MenuItem `Menu` and `MenuItem` have protected constructors --- cocos/2d/CCMenu.h | 26 +- cocos/2d/CCMenuItem.h | 243 ++++++++++-------- cocos/2d/CCParticleExamples.cpp | 44 ++-- cocos/2d/CCParticleExamples.h | 134 ++++++---- .../cocostudio/CCActionObject.cpp | 4 +- .../Classes/ParticleTest/ParticleTest.cpp | 6 +- 6 files changed, 269 insertions(+), 188 deletions(-) diff --git a/cocos/2d/CCMenu.h b/cocos/2d/CCMenu.h index 64c275841a..04aeb831a4 100644 --- a/cocos/2d/CCMenu.h +++ b/cocos/2d/CCMenu.h @@ -73,17 +73,6 @@ public: /** creates a Menu with MenuItem objects */ static Menu* createWithItems(MenuItem *firstItem, va_list args); - /** - * @js ctor - */ - Menu() : _selectedItem(NULL) {} - virtual ~Menu(); - - /** initializes an empty Menu */ - bool init(); - - /** initializes a Menu with a NSArray of MenuItem objects */ - bool initWithArray(Array* pArrayOfItems); /** align items vertically */ void alignItemsVertically(); @@ -130,12 +119,27 @@ public: virtual bool isOpacityModifyRGB(void) const override { return false;} protected: + /** + * @js ctor + */ + Menu() : _selectedItem(NULL) {} + virtual ~Menu(); + + /** initializes an empty Menu */ + bool init(); + + /** initializes a Menu with a NSArray of MenuItem objects */ + bool initWithArray(Array* pArrayOfItems); + /** whether or not the menu will receive events */ bool _enabled; MenuItem* itemForTouch(Touch * touch); State _state; MenuItem *_selectedItem; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Menu); }; // end of GUI group diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index d0fcda9a50..fb44773d27 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -65,31 +65,6 @@ public: CC_DEPRECATED_ATTRIBUTE static MenuItem* create(Object *rec, SEL_MenuHandler selector); /** Creates a MenuItem with a target/selector */ static MenuItem* create(const ccMenuCallback& callback); - /** - * @js ctor - */ - MenuItem() - : _selected(false) - , _enabled(false) - , _callback(nullptr) - , _target(NULL) - {} - /** - * @js NA - * @lua NA - */ - virtual ~MenuItem(); - - /** Initializes a MenuItem with a target/selector - * @js NA - * @lua NA - */ - bool initWithCallback(const ccMenuCallback& callback); - /** Initializes a MenuItem with a target/selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE bool initWithTarget( Object *rec, SEL_MenuHandler selector); /** Returns the outside box */ Rect rect() const; @@ -120,12 +95,41 @@ public: CC_DEPRECATED_ATTRIBUTE void setTarget(Object *rec, SEL_MenuHandler selector); protected: + /** + * @js ctor + */ + MenuItem() + : _selected(false) + , _enabled(false) + , _callback(nullptr) + , _target(NULL) + {} + /** + * @js NA + * @lua NA + */ + virtual ~MenuItem(); + + /** Initializes a MenuItem with a target/selector + * @js NA + * @lua NA + */ + bool initWithCallback(const ccMenuCallback& callback); + /** Initializes a MenuItem with a target/selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE bool initWithTarget( Object *rec, SEL_MenuHandler selector); + bool _selected; bool _enabled; // callback ccMenuCallback _callback; // If using the old API, the _target needs to be retained / released Object *_target; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItem); }; /** @brief An abstract class for "label" MenuItemLabel items @@ -146,24 +150,6 @@ public: /** creates a MenuItemLabel with a Label. Target and selector will be nil */ static MenuItemLabel* create(Node *label); - /** - * @js ctor - */ - MenuItemLabel() - : _originalScale(0.0) - , _label(NULL) - {} - /** - * @js NA - * @lua NA - */ - virtual ~MenuItemLabel(); - - /** initializes a MenuItemLabel with a Label, target and selector */ - bool initWithLabel(Node* label, const ccMenuCallback& callback); - - /** initializes a MenuItemLabel with a Label, target and selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); /** sets a new string to the inner label */ void setString(const std::string& label); @@ -187,6 +173,25 @@ public: virtual void setEnabled(bool enabled) override; protected: + /** + * @js ctor + */ + MenuItemLabel() + : _originalScale(0.0) + , _label(NULL) + {} + /** + * @js NA + * @lua NA + */ + virtual ~MenuItemLabel(); + + /** initializes a MenuItemLabel with a Label, target and selector */ + bool initWithLabel(Node* label, const ccMenuCallback& callback); + + /** initializes a MenuItemLabel with a Label, target and selector */ + CC_DEPRECATED_ATTRIBUTE bool initWithLabel(Node* label, Object* target, SEL_MenuHandler selector); + Color3B _colorBackup; float _originalScale; @@ -194,6 +199,9 @@ protected: Color3B _disabledColor; /** Label that is rendered. It can be any Node that implements the LabelProtocol */ Node* _label; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemLabel); }; @@ -209,6 +217,8 @@ public: CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string and atlas. Use it with MenuItemToggle */ static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); + +protected: /** * @js ctor */ @@ -223,6 +233,9 @@ public: CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, long itemWidth, long itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); /** initializes a menu item from a string and atlas with a target/selector */ bool initWithString(const std::string& value, const std::string& charMapFile, long itemWidth, long itemHeight, char startCharMap, const ccMenuCallback& callback); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemAtlasFont); }; @@ -238,20 +251,6 @@ public: CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string with a target/selector */ static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); - /** - * @js ctor - */ - MenuItemFont(); - /** - * @js NA - * @lua NA - */ - virtual ~MenuItemFont(); - - /** initializes a menu item from a string with a target/selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); - /** initializes a menu item from a string with a target/selector */ - bool initWithString(const std::string& value, const ccMenuCallback& callback); /** set default font size */ static void setFontSize(long size); @@ -293,10 +292,28 @@ public: CC_DEPRECATED_ATTRIBUTE const std::string& fontNameObj() const { return getFontNameObj(); } protected: + /** + * @js ctor + */ + MenuItemFont(); + /** + * @js NA + * @lua NA + */ + virtual ~MenuItemFont(); + + /** initializes a menu item from a string with a target/selector */ + CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); + /** initializes a menu item from a string with a target/selector */ + bool initWithString(const std::string& value, const ccMenuCallback& callback); + void recreateLabel(); long _fontSize; std::string _fontName; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemFont); }; @@ -322,17 +339,6 @@ public: /** creates a menu item with a normal,selected and disabled image with target/selector */ static MenuItemSprite * create(Node* normalSprite, Node* selectedSprite, Node* disabledSprite, const ccMenuCallback& callback); - MenuItemSprite() - :_normalImage(NULL) - ,_selectedImage(NULL) - ,_disabledImage(NULL) - {} - - /** initializes a menu item with a normal, selected and disabled image with target/selector */ - CC_DEPRECATED_ATTRIBUTE bool initWithNormalSprite(Node* normalSprite, Node* selectedSprite, Node* disabledSprite, Object* target, SEL_MenuHandler selector); - /** initializes a menu item with a normal, selected and disabled image with a callable object */ - bool initWithNormalSprite(Node* normalSprite, Node* selectedSprite, Node* disabledSprite, const ccMenuCallback& callback); - /** Gets the image used when the item is not selected */ inline Node* getNormalImage() const { return _normalImage; }; @@ -359,6 +365,17 @@ public: virtual void setEnabled(bool bEnabled); protected: + MenuItemSprite() + :_normalImage(NULL) + ,_selectedImage(NULL) + ,_disabledImage(NULL) + {} + + /** initializes a menu item with a normal, selected and disabled image with target/selector */ + CC_DEPRECATED_ATTRIBUTE bool initWithNormalSprite(Node* normalSprite, Node* selectedSprite, Node* disabledSprite, Object* target, SEL_MenuHandler selector); + /** initializes a menu item with a normal, selected and disabled image with a callable object */ + bool initWithNormalSprite(Node* normalSprite, Node* selectedSprite, Node* disabledSprite, const ccMenuCallback& callback); + virtual void updateImagesVisibility(); /** the image used when the item is not selected */ @@ -367,6 +384,9 @@ protected: Node* _selectedImage; /** the image used when the item is disabled */ Node* _disabledImage; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemSprite); }; @@ -396,6 +416,15 @@ public: CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); /** creates a menu item with a normal,selected and disabled image with a callable object */ static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback); + + /** sets the sprite frame for the normal image */ + void setNormalSpriteFrame(SpriteFrame* frame); + /** sets the sprite frame for the selected image */ + void setSelectedSpriteFrame(SpriteFrame* frame); + /** sets the sprite frame for the disabled image */ + void setDisabledSpriteFrame(SpriteFrame* frame); + +protected: /** * @js ctor */ @@ -412,12 +441,8 @@ public: /** initializes a menu item with a normal, selected and disabled image with a callable object */ bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback); - /** sets the sprite frame for the normal image */ - void setNormalSpriteFrame(SpriteFrame* frame); - /** sets the sprite frame for the selected image */ - void setSelectedSpriteFrame(SpriteFrame* frame); - /** sets the sprite frame for the disabled image */ - void setDisabledSpriteFrame(SpriteFrame* frame); +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemImage); }; @@ -436,39 +461,6 @@ public: static MenuItemToggle* create(); /** creates a menu item with a item */ static MenuItemToggle* create(MenuItem *item); - /** creates a menu item from a Array with a target selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems); - /** creates a menu item from a list of items with a target/selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; - /** - * @js ctor - */ - MenuItemToggle() - : _selectedIndex(0) - , _subItems(NULL) - {} - /** - * @js NA - * @lua NA - */ - virtual ~MenuItemToggle(); - - /** initializes a menu item from a list of items with a target selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, va_list args); - /** initializes a menu item from a list of items with a callable object */ - bool initWithCallback(const ccMenuCallback& callback, MenuItem* item, va_list args); - - /** initializes a menu item with a item */ - bool initWithItem(MenuItem *item); /** add more menu item */ void addSubItem(MenuItem *item); @@ -506,6 +498,40 @@ public: virtual void setEnabled(bool var) override; protected: + /** creates a menu item from a Array with a target selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems); + /** creates a menu item from a list of items with a target/selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; + /** + * @js ctor + */ + MenuItemToggle() + : _selectedIndex(0) + , _subItems(NULL) + {} + /** + * @js NA + * @lua NA + */ + virtual ~MenuItemToggle(); + + /** initializes a menu item from a list of items with a target selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, va_list args); + /** initializes a menu item from a list of items with a callable object */ + bool initWithCallback(const ccMenuCallback& callback, MenuItem* item, va_list args); + + /** initializes a menu item with a item */ + bool initWithItem(MenuItem *item); + /** returns the selected item */ unsigned int _selectedIndex; /** Array that contains the subitems. You can add/remove items in runtime, and you can replace the array with a new one. @@ -513,6 +539,9 @@ protected: */ Array* _subItems; +private: + CC_DISALLOW_COPY_AND_ASSIGN(MenuItemToggle); + }; diff --git a/cocos/2d/CCParticleExamples.cpp b/cocos/2d/CCParticleExamples.cpp index 7120c4b821..2da24c129f 100644 --- a/cocos/2d/CCParticleExamples.cpp +++ b/cocos/2d/CCParticleExamples.cpp @@ -72,7 +72,7 @@ ParticleFire* ParticleFire::create() return pRet; } -ParticleFire* ParticleFire::createWithTotalParticles(unsigned int numberOfParticles) +ParticleFire* ParticleFire::createWithTotalParticles(int numberOfParticles) { ParticleFire* pRet = new ParticleFire(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -86,7 +86,7 @@ ParticleFire* ParticleFire::createWithTotalParticles(unsigned int numberOfPartic return pRet; } -bool ParticleFire::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleFire::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -177,7 +177,7 @@ ParticleFireworks* ParticleFireworks::create() return pRet; } -ParticleFireworks* ParticleFireworks::createWithTotalParticles(unsigned int numberOfParticles) +ParticleFireworks* ParticleFireworks::createWithTotalParticles(int numberOfParticles) { ParticleFireworks* pRet = new ParticleFireworks(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -191,7 +191,7 @@ ParticleFireworks* ParticleFireworks::createWithTotalParticles(unsigned int numb return pRet; } -bool ParticleFireworks::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleFireworks::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -278,7 +278,7 @@ ParticleSun* ParticleSun::create() return pRet; } -ParticleSun* ParticleSun::createWithTotalParticles(unsigned int numberOfParticles) +ParticleSun* ParticleSun::createWithTotalParticles(int numberOfParticles) { ParticleSun* pRet = new ParticleSun(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -292,7 +292,7 @@ ParticleSun* ParticleSun::createWithTotalParticles(unsigned int numberOfParticle return pRet; } -bool ParticleSun::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSun::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -385,7 +385,7 @@ ParticleGalaxy* ParticleGalaxy::create() return pRet; } -ParticleGalaxy* ParticleGalaxy::createWithTotalParticles(unsigned int numberOfParticles) +ParticleGalaxy* ParticleGalaxy::createWithTotalParticles(int numberOfParticles) { ParticleGalaxy* pRet = new ParticleGalaxy(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -399,7 +399,7 @@ ParticleGalaxy* ParticleGalaxy::createWithTotalParticles(unsigned int numberOfPa return pRet; } -bool ParticleGalaxy::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleGalaxy::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -494,7 +494,7 @@ ParticleFlower* ParticleFlower::create() return pRet; } -ParticleFlower* ParticleFlower::createWithTotalParticles(unsigned int numberOfParticles) +ParticleFlower* ParticleFlower::createWithTotalParticles(int numberOfParticles) { ParticleFlower* pRet = new ParticleFlower(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -508,7 +508,7 @@ ParticleFlower* ParticleFlower::createWithTotalParticles(unsigned int numberOfPa return pRet; } -bool ParticleFlower::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleFlower::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -602,7 +602,7 @@ ParticleMeteor * ParticleMeteor::create() return pRet; } -ParticleMeteor* ParticleMeteor::createWithTotalParticles(unsigned int numberOfParticles) +ParticleMeteor* ParticleMeteor::createWithTotalParticles(int numberOfParticles) { ParticleMeteor* pRet = new ParticleMeteor(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -616,7 +616,7 @@ ParticleMeteor* ParticleMeteor::createWithTotalParticles(unsigned int numberOfPa return pRet; } -bool ParticleMeteor::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleMeteor::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -711,7 +711,7 @@ ParticleSpiral* ParticleSpiral::create() return pRet; } -ParticleSpiral* ParticleSpiral::createWithTotalParticles(unsigned int numberOfParticles) +ParticleSpiral* ParticleSpiral::createWithTotalParticles(int numberOfParticles) { ParticleSpiral* pRet = new ParticleSpiral(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -725,7 +725,7 @@ ParticleSpiral* ParticleSpiral::createWithTotalParticles(unsigned int numberOfPa return pRet; } -bool ParticleSpiral::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSpiral::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -820,7 +820,7 @@ ParticleExplosion* ParticleExplosion::create() return pRet; } -ParticleExplosion* ParticleExplosion::createWithTotalParticles(unsigned int numberOfParticles) +ParticleExplosion* ParticleExplosion::createWithTotalParticles(int numberOfParticles) { ParticleExplosion* pRet = new ParticleExplosion(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -834,7 +834,7 @@ ParticleExplosion* ParticleExplosion::createWithTotalParticles(unsigned int numb return pRet; } -bool ParticleExplosion::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleExplosion::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -928,7 +928,7 @@ ParticleSmoke* ParticleSmoke::create() return pRet; } -ParticleSmoke* ParticleSmoke::createWithTotalParticles(unsigned int numberOfParticles) +ParticleSmoke* ParticleSmoke::createWithTotalParticles(int numberOfParticles) { ParticleSmoke* pRet = new ParticleSmoke(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -942,7 +942,7 @@ ParticleSmoke* ParticleSmoke::createWithTotalParticles(unsigned int numberOfPart return pRet; } -bool ParticleSmoke::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSmoke::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -1033,7 +1033,7 @@ ParticleSnow* ParticleSnow::create() return pRet; } -ParticleSnow* ParticleSnow::createWithTotalParticles(unsigned int numberOfParticles) +ParticleSnow* ParticleSnow::createWithTotalParticles(int numberOfParticles) { ParticleSnow* pRet = new ParticleSnow(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -1047,7 +1047,7 @@ ParticleSnow* ParticleSnow::createWithTotalParticles(unsigned int numberOfPartic return pRet; } -bool ParticleSnow::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleSnow::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { @@ -1141,7 +1141,7 @@ ParticleRain* ParticleRain::create() return pRet; } -ParticleRain* ParticleRain::createWithTotalParticles(unsigned int numberOfParticles) +ParticleRain* ParticleRain::createWithTotalParticles(int numberOfParticles) { ParticleRain* pRet = new ParticleRain(); if (pRet && pRet->initWithTotalParticles(numberOfParticles)) @@ -1155,7 +1155,7 @@ ParticleRain* ParticleRain::createWithTotalParticles(unsigned int numberOfPartic return pRet; } -bool ParticleRain::initWithTotalParticles(unsigned int numberOfParticles) +bool ParticleRain::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { diff --git a/cocos/2d/CCParticleExamples.h b/cocos/2d/CCParticleExamples.h index f8d36d28d4..325bcd59f9 100644 --- a/cocos/2d/CCParticleExamples.h +++ b/cocos/2d/CCParticleExamples.h @@ -39,6 +39,10 @@ NS_CC_BEGIN class CC_DLL ParticleFire : public ParticleSystemQuad { public: + static ParticleFire* create(); + static ParticleFire* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -49,16 +53,20 @@ public: */ virtual ~ParticleFire(){} bool init(){ return initWithTotalParticles(250); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleFire* create(); - static ParticleFire* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles) override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleFire); }; //! @brief A fireworks particle system class CC_DLL ParticleFireworks : public ParticleSystemQuad { public: + static ParticleFireworks* create(); + static ParticleFireworks* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -69,16 +77,21 @@ public: */ virtual ~ParticleFireworks(){} bool init(){ return initWithTotalParticles(1500); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleFireworks* create(); - static ParticleFireworks* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleFireworks); + }; //! @brief A sun particle system class CC_DLL ParticleSun : public ParticleSystemQuad { public: + static ParticleSun* create(); + static ParticleSun* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -89,16 +102,21 @@ public: */ virtual ~ParticleSun(){} bool init(){ return initWithTotalParticles(350); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleSun* create(); - static ParticleSun* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSun); + }; //! @brief A galaxy particle system class CC_DLL ParticleGalaxy : public ParticleSystemQuad { public: + static ParticleGalaxy* create(); + static ParticleGalaxy* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -109,16 +127,21 @@ public: */ virtual ~ParticleGalaxy(){} bool init(){ return initWithTotalParticles(200); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleGalaxy* create(); - static ParticleGalaxy* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleGalaxy); + }; //! @brief A flower particle system class CC_DLL ParticleFlower : public ParticleSystemQuad { public: + static ParticleFlower* create(); + static ParticleFlower* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -129,16 +152,20 @@ public: */ virtual ~ParticleFlower(){} bool init(){ return initWithTotalParticles(250); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleFlower* create(); - static ParticleFlower* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleFlower); }; //! @brief A meteor particle system class CC_DLL ParticleMeteor : public ParticleSystemQuad { public: + static ParticleMeteor * create(); + static ParticleMeteor* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -149,16 +176,20 @@ public: */ virtual ~ParticleMeteor(){} bool init(){ return initWithTotalParticles(150); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); - static ParticleMeteor * create(); - static ParticleMeteor* createWithTotalParticles(unsigned int numberOfParticles); +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleMeteor); }; //! @brief An spiral particle system class CC_DLL ParticleSpiral : public ParticleSystemQuad { public: + static ParticleSpiral* create(); + static ParticleSpiral* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -169,16 +200,21 @@ public: */ virtual ~ParticleSpiral(){} bool init(){ return initWithTotalParticles(500); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleSpiral* create(); - static ParticleSpiral* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSpiral); + }; //! @brief An explosion particle system class CC_DLL ParticleExplosion : public ParticleSystemQuad { public: + static ParticleExplosion* create(); + static ParticleExplosion* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -189,16 +225,20 @@ public: */ virtual ~ParticleExplosion(){} bool init(){ return initWithTotalParticles(700); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleExplosion* create(); - static ParticleExplosion* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleExplosion); }; //! @brief An smoke particle system class CC_DLL ParticleSmoke : public ParticleSystemQuad { public: + static ParticleSmoke* create(); + static ParticleSmoke* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -209,16 +249,20 @@ public: */ virtual ~ParticleSmoke(){} bool init(){ return initWithTotalParticles(200); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleSmoke* create(); - static ParticleSmoke* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSmoke); }; //! @brief An snow particle system class CC_DLL ParticleSnow : public ParticleSystemQuad { public: + static ParticleSnow* create(); + static ParticleSnow* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -229,16 +273,20 @@ public: */ virtual ~ParticleSnow(){} bool init(){ return initWithTotalParticles(700); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleSnow* create(); - static ParticleSnow* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleSnow); }; //! @brief A rain particle system class CC_DLL ParticleRain : public ParticleSystemQuad { public: + static ParticleRain* create(); + static ParticleRain* createWithTotalParticles(int numberOfParticles); + +protected: /** * @js ctor */ @@ -249,10 +297,10 @@ public: */ virtual ~ParticleRain(){} bool init(){ return initWithTotalParticles(1000); } - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - - static ParticleRain* create(); - static ParticleRain* createWithTotalParticles(unsigned int numberOfParticles); + virtual bool initWithTotalParticles(int numberOfParticles); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ParticleRain); }; // end of particle_nodes group diff --git a/cocos/editor-support/cocostudio/CCActionObject.cpp b/cocos/editor-support/cocostudio/CCActionObject.cpp index ba12778510..5d9a85e587 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/CCActionObject.cpp @@ -42,7 +42,7 @@ ActionObject::ActionObject() _actionNodeList = Array::create(); _actionNodeList->retain(); _pScheduler = new Scheduler(); - Director::sharedDirector()->getScheduler()->scheduleUpdateForTarget(_pScheduler, 0, false); + Director::getInstance()->getScheduler()->scheduleUpdateForTarget(_pScheduler, 0, false); } ActionObject::~ActionObject() @@ -193,7 +193,7 @@ void ActionObject::simulationActionUpdate(float dt) for ( int i = 0; i < nodeNum; i++ ) { - ActionNode* actionNode = (ActionNode*)_actionNodeList->objectAtIndex(i); + ActionNode* actionNode = static_cast(_actionNodeList->getObjectAtIndex(i)); if (actionNode->isActionDoneOnce() == false) { diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index 88fd2cebd2..f8bfc895af 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1379,8 +1379,8 @@ class RainbowEffect : public ParticleSystemQuad { public: bool init(); - virtual bool initWithTotalParticles(unsigned int numberOfParticles); - virtual void update(float dt); + virtual bool initWithTotalParticles(int numberOfParticles) override; + virtual void update(float dt) override; }; bool RainbowEffect::init() @@ -1388,7 +1388,7 @@ bool RainbowEffect::init() return initWithTotalParticles(150); } -bool RainbowEffect::initWithTotalParticles(unsigned int numberOfParticles) +bool RainbowEffect::initWithTotalParticles(int numberOfParticles) { if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) { From a3fabd6b6df77571b2b37b280daafcafc43426f3 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 15 Nov 2013 16:37:57 -0800 Subject: [PATCH 11/75] TiledMap uses std::string --- cocos/2d/CCTileMapAtlas.cpp | 8 +++----- cocos/2d/CCTileMapAtlas.h | 11 ++++++----- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/cocos/2d/CCTileMapAtlas.cpp b/cocos/2d/CCTileMapAtlas.cpp index 9b7bc85ad3..8dc22d8244 100644 --- a/cocos/2d/CCTileMapAtlas.cpp +++ b/cocos/2d/CCTileMapAtlas.cpp @@ -36,7 +36,7 @@ NS_CC_BEGIN // implementation TileMapAtlas -TileMapAtlas * TileMapAtlas::create(const char *tile, const char *mapFile, int tileWidth, int tileHeight) +TileMapAtlas * TileMapAtlas::create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) { TileMapAtlas *pRet = new TileMapAtlas(); if (pRet->initWithTileFile(tile, mapFile, tileWidth, tileHeight)) @@ -48,7 +48,7 @@ TileMapAtlas * TileMapAtlas::create(const char *tile, const char *mapFile, int t return NULL; } -bool TileMapAtlas::initWithTileFile(const char *tile, const char *mapFile, int tileWidth, int tileHeight) +bool TileMapAtlas::initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight) { this->loadTGAfile(mapFile); this->calculateItemsToRender(); @@ -111,10 +111,8 @@ void TileMapAtlas::calculateItemsToRender() } } -void TileMapAtlas::loadTGAfile(const char *file) +void TileMapAtlas::loadTGAfile(const std::string& file) { - CCASSERT( file != NULL, "file must be non-nil"); - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(file); // //Find the path of the file diff --git a/cocos/2d/CCTileMapAtlas.h b/cocos/2d/CCTileMapAtlas.h index 865f47295a..e9899366d4 100644 --- a/cocos/2d/CCTileMapAtlas.h +++ b/cocos/2d/CCTileMapAtlas.h @@ -60,7 +60,7 @@ public: /** creates a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The tile file will be loaded using the TextureMgr. */ - static TileMapAtlas * create(const char *tile, const char *mapFile, int tileWidth, int tileHeight); + static TileMapAtlas * create(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); /** * @js ctor */ @@ -74,7 +74,7 @@ public: /** initializes a TileMap with a tile file (atlas) with a map file and the width and height of each tile in points. The file will be loaded using the TextureMgr. */ - bool initWithTileFile(const char *tile, const char *mapFile, int tileWidth, int tileHeight); + bool initWithTileFile(const std::string& tile, const std::string& mapFile, int tileWidth, int tileHeight); /** returns a tile from position x,y. For the moment only channel R is used */ @@ -89,13 +89,14 @@ public: inline struct sImageTGA* getTGAInfo() const { return _TGAInfo; }; inline void setTGAInfo(struct sImageTGA* TGAInfo) { _TGAInfo = TGAInfo; }; -private: - void loadTGAfile(const char *file); + +protected: + void loadTGAfile(const std::string& file); void calculateItemsToRender(); void updateAtlasValueAt(const Point& pos, const Color3B& value, int index); void updateAtlasValues(); -protected: + //! x,y to atlas dictionary Dictionary* _posToAtlasIndex; //! numbers of tiles to render From 627b9538d0ccbbc0b77566fc042801d2f3f57410 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 21 Nov 2013 10:48:21 +0800 Subject: [PATCH 12/75] issue #2771: fix physics test CC_USE_PHYSICS definition --- .../Classes/PhysicsTest/PhysicsTest.cpp | 55 ++++++++++--------- .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 14 +++-- 2 files changed, 40 insertions(+), 29 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index a9eca9a6ad..4acaf61418 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -6,6 +6,7 @@ USING_NS_CC; namespace { static std::function createFunctions[] = { +#ifdef CC_USE_PHYSICS CL(PhysicsDemoLogoSmash), CL(PhysicsDemoPyramidStack), CL(PhysicsDemoClickAdd), @@ -15,6 +16,9 @@ namespace CL(PhysicsDemoPump), CL(PhysicsDemoOneWayPlatform), CL(PhysicsDemoSlice), +#else + CL(PhysicsDemoDisabled), +#endif }; static int sceneIdx=-1; @@ -59,23 +63,44 @@ namespace static const int DRAG_BODYS_TAG = 0x80; } +PhysicsTestScene::PhysicsTestScene() +#ifdef CC_USE_PHYSICS +: TestScene(false, true) +#else +: TestScene() +#endif +, _debugDraw(false) +{} + void PhysicsTestScene::runThisTest() { -#ifdef CC_USE_PHYSICS sceneIdx = -1; addChild(next()); Director::getInstance()->replaceScene(this); -#else -#endif } void PhysicsTestScene::toggleDebug() { +#ifdef CC_USE_PHYSICS _debugDraw = !_debugDraw; getPhysicsWorld()->setDebugDrawMask(_debugDraw ? PhysicsWorld::DEBUGDRAW_ALL : PhysicsWorld::DEBUGDRAW_NONE); +#endif } +#ifndef CC_USE_PHYSICS +void PhysicsDemoDisabled::onEnter() +{ + auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", + "Arial", + 18); + auto size = Director::getInstance()->getWinSize(); + label->setPosition(Point(size.width/2, size.height/2)); + + addChild(label); +} +#else + PhysicsDemo::PhysicsDemo() : _scene(nullptr) , _spriteTexture(nullptr) @@ -130,8 +155,6 @@ void PhysicsDemo::onEnter() _spriteTexture = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100)->getTexture(); -#ifdef CC_USE_PHYSICS - // menu for debug layer MenuItemFont::setFontSize(18); auto item = MenuItemFont::create("Toggle debug", CC_CALLBACK_1(PhysicsDemo::toggleDebugCallback, this)); @@ -139,13 +162,10 @@ void PhysicsDemo::onEnter() auto menu = Menu::create(item, NULL); this->addChild(menu); menu->setPosition(Point(VisibleRect::right().x-50, VisibleRect::top().y-10)); -#else -#endif } Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) { -#ifdef CC_USE_PHYSICS CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); int posx, posy; @@ -163,18 +183,15 @@ Sprite* PhysicsDemo::addGrossiniAtPosition(Point p, float scale/* = 1.0*/) sp->setPosition(p); return sp; -#endif } void PhysicsDemo::toggleDebugCallback(Object* sender) { -#ifdef CC_USE_PHYSICS if (_scene != nullptr) { _scene->toggleDebug(); } -#endif } PhysicsDemoClickAdd::~PhysicsDemoClickAdd() @@ -186,8 +203,6 @@ void PhysicsDemoClickAdd::onEnter() { PhysicsDemo::onEnter(); -#ifdef CC_USE_PHYSICS - auto touchListener = EventListenerTouchAllAtOnce::create(); touchListener->onTouchesEnded = CC_CALLBACK_2(PhysicsDemoClickAdd::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); @@ -202,16 +217,6 @@ void PhysicsDemoClickAdd::onEnter() this->addChild(node); addGrossiniAtPosition(VisibleRect::center()); - -#else - auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", - "Arial", - 18); - auto size = Director::getInstance()->getWinSize(); - label->setPosition(Point(size.width/2, size.height/2)); - - addChild(label); -#endif } std::string PhysicsDemoClickAdd::subtitle() @@ -233,7 +238,6 @@ void PhysicsDemoClickAdd::onTouchesEnded(const std::vector& touches, Eve void PhysicsDemoClickAdd::onAcceleration(Acceleration* acc, Event* event) { -#ifdef CC_USE_PHYSICS static float prevX=0, prevY=0; #define kFilterFactor 0.05f @@ -251,7 +255,6 @@ void PhysicsDemoClickAdd::onAcceleration(Acceleration* acc, Event* event) { _scene->getPhysicsWorld()->setGravity(v); } -#endif } namespace @@ -1121,3 +1124,5 @@ std::string PhysicsDemoSlice::subtitle() { return "click and drag to slice up the block"; } + +#endif // ifndef CC_USE_PHYSICS \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index b306b59352..663374f9a9 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -11,10 +11,7 @@ class PhysicsTestScene : public TestScene { public: - PhysicsTestScene() - :TestScene(false, true) - , _debugDraw(false) - {} + PhysicsTestScene(); public: virtual void runThisTest(); @@ -25,6 +22,14 @@ private: bool _debugDraw; }; +#ifndef CC_USE_PHYSICS +class PhysicsDemoDisabled : public BaseTest +{ +public: + virtual void onEnter() override; +}; +#else + class PhysicsDemo : public BaseTest { public: @@ -160,3 +165,4 @@ private: }; #endif +#endif From 8e14cdb8d21f20dbbc114282b51e7b6bb4aefcdc Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 21 Nov 2013 14:39:37 +0800 Subject: [PATCH 13/75] issue #2771: add assert to joint --- cocos/physics/CCPhysicsJoint.cpp | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index a2b10c8b9c..f28095cfa9 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -71,19 +71,15 @@ bool PhysicsJoint::init(cocos2d::PhysicsBody *a, cocos2d::PhysicsBody *b) { do { + CCASSERT(a != nullptr && b != nullptr, "the body passed in is nil"); + CCASSERT(a != b, "the two bodies are equal"); + CC_BREAK_IF(!(_info = new PhysicsJointInfo(this))); - if (a != nullptr) - { - _bodyA = a; - _bodyA->_joints.push_back(this); - } - - if (b != nullptr) - { - _bodyB = b; - _bodyB->_joints.push_back(this); - } + _bodyA = a; + _bodyA->_joints.push_back(this); + _bodyB = b; + _bodyB->_joints.push_back(this); return true; } while (false); From b6ddc6d048b15712cd25e3dbd99ea7596615ca90 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 21 Nov 2013 13:43:59 -0800 Subject: [PATCH 14/75] Uses std::unordered_map<> instead of std::map<> and more fixes. --- cocos/2d/CCTMXXMLParser.cpp | 8 ++--- cocos/2d/CCTexture2D.h | 1 + cocos/2d/ZipUtils.cpp | 2 +- cocos/2d/platform/CCFileUtils.h | 4 +-- cocos/2d/platform/mac/CCEGLView.mm | 6 +++- cocos/network/SocketIO.h | 2 +- .../chipmunk/CCPhysicsJointInfo_chipmunk.cpp | 5 ++- .../chipmunk/CCPhysicsJointInfo_chipmunk.h | 9 +++--- .../chipmunk/CCPhysicsShapeInfo_chipmunk.cpp | 5 ++- .../chipmunk/CCPhysicsShapeInfo_chipmunk.h | 12 +++---- .../javascript/bindings/ScriptingCore.cpp | 6 ++-- .../javascript/bindings/cocos2d_specifics.hpp | 2 +- .../bindings/network/XMLHTTPRequest.h | 4 +-- extensions/GUI/CCControlExtension/CCControl.h | 28 +++++++++------- .../CCControlExtension/CCControlButton.cpp | 24 +++++++------- .../GUI/CCControlExtension/CCControlButton.h | 32 +++++++------------ .../TestCpp/Classes/PhysicsTest/PhysicsTest.h | 2 +- 17 files changed, 78 insertions(+), 74 deletions(-) diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 5abe1e6f31..06a25e3e37 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -25,7 +25,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include +#include #include #include "CCTMXXMLParser.h" #include "CCTMXTiledMap.h" @@ -38,11 +38,11 @@ using namespace std; NS_CC_BEGIN -static const char* valueForKey(const char *key, std::map* dict) +static const char* valueForKey(const char *key, std::unordered_map* dict) { if (dict) { - std::map::iterator it = dict->find(key); + std::unordered_map::iterator it = dict->find(key); return it!=dict->end() ? it->second.c_str() : ""; } return ""; @@ -244,7 +244,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) CC_UNUSED_PARAM(ctx); TMXMapInfo *pTMXMapInfo = this; std::string elementName = (char*)name; - std::map *attributeDict = new std::map(); + std::unordered_map *attributeDict = new std::unordered_map(); if (atts && atts[0]) { for(int i = 0; atts[i]; i += 2) diff --git a/cocos/2d/CCTexture2D.h b/cocos/2d/CCTexture2D.h index bdb28ce582..96c861c341 100644 --- a/cocos/2d/CCTexture2D.h +++ b/cocos/2d/CCTexture2D.h @@ -28,6 +28,7 @@ THE SOFTWARE. #include #include +#include #include "CCObject.h" #include "CCGeometry.h" diff --git a/cocos/2d/ZipUtils.cpp b/cocos/2d/ZipUtils.cpp index 26681d7bca..ebde2f9963 100644 --- a/cocos/2d/ZipUtils.cpp +++ b/cocos/2d/ZipUtils.cpp @@ -511,7 +511,7 @@ public: unzFile zipFile; // std::unordered_map is faster if available on the platform - typedef std::map FileListContainer; + typedef std::unordered_map FileListContainer; FileListContainer fileList; }; diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 1827ba53c7..672e4b7234 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -26,7 +26,7 @@ THE SOFTWARE. #include #include -#include +#include #include "CCPlatformMacros.h" #include "ccTypes.h" @@ -399,7 +399,7 @@ protected: * The full path cache. When a file is found, it will be added into this cache. * This variable is used for improving the performance of file search. */ - std::map _fullPathCache; + std::unordered_map _fullPathCache; /** * The singleton pointer of FileUtils. diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index d66f1dc17c..04ef6b69e7 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -21,7 +21,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + #include "CCEGLView.h" + +#include + #include "EAGLView.h" #include "CCDirector.h" #include "CCSet.h" @@ -34,7 +38,7 @@ NS_CC_BEGIN -static std::map g_keyCodeMap = { +static std::unordered_map g_keyCodeMap = { /* The unknown key */ { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, diff --git a/cocos/network/SocketIO.h b/cocos/network/SocketIO.h index 5ec76bcb9b..7d62ed65a9 100644 --- a/cocos/network/SocketIO.h +++ b/cocos/network/SocketIO.h @@ -116,7 +116,7 @@ private: //c++11 style callbacks entities will be created using CC_CALLBACK (which uses std::bind) typedef std::function SIOEvent; //c++11 map to callbacks -typedef std::map EventRegistry; +typedef std::unordered_map EventRegistry; /** * @brief A single connection to a socket.io endpoint diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index 2f8b7817cf..dd281507ea 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -23,11 +23,14 @@ ****************************************************************************/ #include "CCPhysicsJointInfo_chipmunk.h" + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include +#include + NS_CC_BEGIN -std::map PhysicsJointInfo::_map; +std::unordered_map PhysicsJointInfo::_map; PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) : _joint(joint) diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index bdd3f1e887..9243d268be 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -31,7 +31,7 @@ #include "chipmunk.h" #include "CCPlatformMacros.h" #include -#include +#include NS_CC_BEGIN class PhysicsJoint; @@ -45,16 +45,15 @@ public: PhysicsJoint* getJoint() const { return _joint; } std::vector& getJoints() { return _joints; } - static std::map& getMap() { return _map; } + static std::unordered_map& getMap() { return _map; } -private: +protected: PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); -private: std::vector _joints; PhysicsJoint* _joint; - static std::map _map; + static std::unordered_map _map; friend class PhysicsJoint; }; diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index d12a053181..62780c1fb1 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -23,11 +23,14 @@ ****************************************************************************/ #include "CCPhysicsShapeInfo_chipmunk.h" + #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include +#include + NS_CC_BEGIN -std::map PhysicsShapeInfo::_map; +std::unordered_map PhysicsShapeInfo::_map; cpBody* PhysicsShapeInfo::_sharedBody = nullptr; PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 2bdd55a7f9..d46246673e 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -29,7 +29,7 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include -#include +#include #include "chipmunk.h" #include "CCPlatformMacros.h" @@ -45,25 +45,23 @@ public: void removeAll(); void setGroup(cpGroup group); void setBody(cpBody* body); - -public: + PhysicsShape* getShape() const { return _shape; } std::vector& getShapes() { return _shapes; } cpBody* getBody() const { return _body; } cpGroup getGourp() const { return _group; } - static std::map& getMap() { return _map; } + static std::unordered_map& getMap() { return _map; } static cpBody* getSharedBody() { return _sharedBody; } -private: +protected: PhysicsShapeInfo(PhysicsShape* shape); ~PhysicsShapeInfo(); -private: std::vector _shapes; PhysicsShape* _shape; cpBody* _body; cpGroup _group; - static std::map _map; + static std::unordered_map _map; static cpBody* _sharedBody; friend class PhysicsShape; diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 0f7fca11f4..bbef7a525d 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -74,11 +74,11 @@ static char *_js_log_buf = NULL; static std::vector registrationList; // name ~> JSScript map -static std::map filename_script; +static std::unordered_map filename_script; // port ~> socket map -static std::map ports_sockets; +static std::unordered_map ports_sockets; // name ~> globals -static std::map globals; +static std::unordered_map globals; static void ReportException(JSContext *cx) { diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index 9c03489007..25cca6ef30 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -191,7 +191,7 @@ public: private: JSObject* _obj; - typedef std::map TouchDelegateMap; + typedef std::unordered_map TouchDelegateMap; typedef std::pair TouchDelegatePair; static TouchDelegateMap sTouchDelegateMap; bool _needUnroot; diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h index 93951313f4..7a4be6b822 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -105,8 +105,8 @@ private: network::HttpRequest* _httpRequest; bool _isNetwork; bool _withCredentialsValue; - std::map _httpHeader; - std::map _requestHeader; + std::unordered_map _httpHeader; + std::unordered_map _requestHeader; }; #endif diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index 12533f7041..a86970e1d8 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -89,18 +89,9 @@ public: DISABLED = 1 << 2, // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. SELECTED = 1 << 3 // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. }; - + + /** Creates a Control object */ static Control* create(); - /** - * @js ctor - */ - Control(); - virtual bool init(void); - /** - * @js NA - * @lua NA - */ - virtual ~Control(); /** Tells whether the control is enabled. */ virtual void setEnabled(bool bEnabled); @@ -184,6 +175,17 @@ public: virtual void setOpacityModifyRGB(bool bOpacityModifyRGB) override; protected: + /** + * @js ctor + */ + Control(); + virtual bool init(void); + /** + * @js NA + * @lua NA + */ + virtual ~Control(); + /** * Returns an Invocation object able to construct messages using a given * target-action pair. (The invocation may optionnaly include the sender and @@ -240,7 +242,6 @@ protected: */ void removeTargetWithActionForControlEvent(Object* target, Handler action, EventType controlEvent); -protected: bool _enabled; bool _selected; bool _highlighted; @@ -260,6 +261,9 @@ protected: /** The current control state constant. */ CC_SYNTHESIZE_READONLY(State, _state, State); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Control); }; Control::EventType operator|(Control::EventType a, Control::EventType b); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.cpp b/extensions/GUI/CCControlExtension/CCControlButton.cpp index db18da4cdd..278338efe1 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.cpp +++ b/extensions/GUI/CCControlExtension/CCControlButton.cpp @@ -151,13 +151,13 @@ ControlButton* ControlButton::create(Node* label, Scale9Sprite* backgroundSprite return pRet; } -bool ControlButton::initWithTitleAndFontNameAndFontSize(string title, const char * fontName, float fontSize) +bool ControlButton::initWithTitleAndFontNameAndFontSize(const std::string& title, const std::string& fontName, float fontSize) { - LabelTTF *label = LabelTTF::create(title.c_str(), fontName, fontSize); + LabelTTF *label = LabelTTF::create(title, fontName, fontSize); return initWithLabelAndBackgroundSprite(label, Scale9Sprite::create()); } -ControlButton* ControlButton::create(string title, const char * fontName, float fontSize) +ControlButton* ControlButton::create(const std::string& title, const std::string& fontName, float fontSize) { ControlButton *pRet = new ControlButton(); pRet->initWithTitleAndFontNameAndFontSize(title, fontName, fontSize); @@ -237,7 +237,7 @@ bool ControlButton::getZoomOnTouchDown() return _zoomOnTouchDown; } -void ControlButton::setPreferredSize(Size size) +void ControlButton::setPreferredSize(const Size& size) { if(size.width == 0 && size.height == 0) { @@ -258,7 +258,7 @@ void ControlButton::setPreferredSize(Size size) needsLayout(); } -Size ControlButton::getPreferredSize() +const Size& ControlButton::getPreferredSize() const { return _preferredSize; } @@ -274,12 +274,12 @@ bool ControlButton::doesAdjustBackgroundImage() return _doesAdjustBackgroundImage; } -Point ControlButton::getLabelAnchorPoint() +const Point& ControlButton::getLabelAnchorPoint() const { return this->_labelAnchorPoint; } -void ControlButton::setLabelAnchorPoint(Point labelAnchorPoint) +void ControlButton::setLabelAnchorPoint(const Point& labelAnchorPoint) { this->_labelAnchorPoint = labelAnchorPoint; if (_titleLabel != NULL) @@ -292,12 +292,12 @@ String* ControlButton::getTitleForState(State state) { if (_titleDispatchTable != NULL) { - String* title=(String*)_titleDispatchTable->objectForKey((int)state); + String* title = static_cast(_titleDispatchTable->objectForKey((int)state)); if (title) { return title; } - return (String*)_titleDispatchTable->objectForKey((int)Control::State::NORMAL); + return static_cast(_titleDispatchTable->objectForKey((int)Control::State::NORMAL)); } return String::create(""); } @@ -342,7 +342,7 @@ Color3B ControlButton::getTitleColorForState(State state) const return returnColor; } -void ControlButton::setTitleColorForState(Color3B color, State state) +void ControlButton::setTitleColorForState(const Color3B& color, State state) { //Color3B* colorValue=&color; _titleColorDispatchTable->removeObjectForKey((int)state); @@ -359,7 +359,7 @@ void ControlButton::setTitleColorForState(Color3B color, State state) Node* ControlButton::getTitleLabelForState(State state) { - Node* titleLabel = (Node*)_titleLabelDispatchTable->objectForKey((int)state); + Node* titleLabel = static_cast(_titleLabelDispatchTable->objectForKey((int)state)); if (titleLabel) { return titleLabel; @@ -369,7 +369,7 @@ Node* ControlButton::getTitleLabelForState(State state) void ControlButton::setTitleLabelForState(Node* titleLabel, State state) { - Node* previousLabel = (Node*)_titleLabelDispatchTable->objectForKey((int)state); + Node* previousLabel = static_cast(_titleLabelDispatchTable->objectForKey((int)state)); if (previousLabel) { removeChild(previousLabel, true); diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index 1da0d5c74d..2cbadab7df 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -56,7 +56,7 @@ public: static ControlButton* create(); static ControlButton* create(Scale9Sprite* sprite); static ControlButton* create(Node* label, Scale9Sprite* backgroundSprite); - static ControlButton* create(std::string title, const char * fontName, float fontSize); + static ControlButton* create(const std::string& title, const std::string& fontName, float fontSize); virtual void needsLayout(void); @@ -105,7 +105,7 @@ public: * @param state The state that uses the specified color. The values are described * in "CCControlState". */ - virtual void setTitleColorForState(Color3B color, State state); + virtual void setTitleColorForState(const Color3B& color, State state); /** * Returns the title label used for a state. @@ -170,29 +170,21 @@ public: //set the margins at once (so we only have to do one call of needsLayout) virtual void setMargins(int marginH, int marginV); + /** Adjust the background image. YES by default. If the property is set to NO, the + background will use the prefered size of the background image. */ + bool doesAdjustBackgroundImage(); + void setAdjustBackgroundImage(bool adjustBackgroundImage); + + // Overrides virtual bool onTouchBegan(Touch *touch, Event *event) override; virtual void onTouchMoved(Touch *touch, Event *event) override; virtual void onTouchEnded(Touch *touch, Event *event) override; virtual void onTouchCancelled(Touch *touch, Event *event) override; - - // Overrides -// virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) override; -// virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) override; virtual GLubyte getOpacity(void) const override; virtual void setOpacity(GLubyte var) override; virtual const Color3B& getColor(void) const override; virtual void setColor(const Color3B&) override; -//protected: - // RGBAProtocol - //bool _isOpacityModifyRGB; - - /** Adjust the background image. YES by default. If the property is set to NO, the - background will use the prefered size of the background image. */ - bool doesAdjustBackgroundImage(); - void setAdjustBackgroundImage(bool adjustBackgroundImage); protected: /** @@ -208,7 +200,7 @@ protected: virtual bool init(); virtual bool initWithLabelAndBackgroundSprite(Node* label, Scale9Sprite* backgroundSprite); virtual bool initWithBackgroundSprite(Scale9Sprite* sprite); - virtual bool initWithTitleAndFontNameAndFontSize(std::string title, const char * fontName, float fontSize); + virtual bool initWithTitleAndFontNameAndFontSize(const std::string& title, const std::string& fontName, float fontSize); bool _isPushed; bool _parentInited; @@ -227,12 +219,12 @@ protected: CC_SYNTHESIZE_RETAIN(Scale9Sprite*, _backgroundSprite, BackgroundSprite); /** The prefered size of the button, if label is larger it will be expanded. */ - CC_PROPERTY(Size, _preferredSize, PreferredSize); + CC_PROPERTY_PASS_BY_REF(Size, _preferredSize, PreferredSize); /** Adjust the button zooming on touchdown. Default value is YES. */ CC_PROPERTY(bool, _zoomOnTouchDown, ZoomOnTouchDown); - CC_PROPERTY(Point, _labelAnchorPoint, LabelAnchorPoint); + CC_PROPERTY_PASS_BY_REF(Point, _labelAnchorPoint, LabelAnchorPoint); // CC_SYNTHESIZE_RETAIN(Dictionary*, _titleDispatchTable, TitleDispatchTable); @@ -248,7 +240,7 @@ protected: /* Define the button margin for Left/Right edge */ CC_SYNTHESIZE_READONLY(int, _marginH, HorizontalOrigin); -protected: +private: CC_DISALLOW_COPY_AND_ASSIGN(ControlButton); }; diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h index 47930e451d..f59992cead 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h @@ -55,7 +55,7 @@ protected: PhysicsTestScene* _scene; Texture2D* _spriteTexture; // weak ref SpriteBatchNode* _ball; - std::map _mouses; + std::unordered_map _mouses; }; class PhysicsDemoClickAdd : public PhysicsDemo From 515786a7eef09d784c79cc13314d90c1e1a66f9e Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 21 Nov 2013 17:06:06 -0800 Subject: [PATCH 15/75] adds CC_DISALLOW_COPY_AND_ASSIGN() to Actilons ... and also moves the Contructor/Destrucotor/initXXX to `protected:` --- cocos/2d/CCAction.h | 111 ++++++----- cocos/2d/CCActionEase.h | 177 ++++++++++++++++-- cocos/2d/CCActionInstant.h | 204 +++++++++++---------- cocos/2d/CCActionInterval.cpp | 20 +- cocos/2d/CCActionInterval.h | 334 +++++++++++++++++++++------------- 5 files changed, 541 insertions(+), 305 deletions(-) diff --git a/cocos/2d/CCAction.h b/cocos/2d/CCAction.h index 21a72591e9..202adf7847 100644 --- a/cocos/2d/CCAction.h +++ b/cocos/2d/CCAction.h @@ -46,15 +46,6 @@ class CC_DLL Action : public Object, public Clonable public: /// Default tag used for all the actions static const int INVALID_TAG = -1; - /** - * @js ctor - */ - Action(); - /** - * @js NA - * @lua NA - */ - virtual ~Action(); /** * @js NA * @lua NA @@ -108,6 +99,9 @@ public: inline void setTag(int tag) { _tag = tag; } protected: + Action(); + virtual ~Action(); + Node *_originalTarget; /** The "target". The target will be set with the 'startWithTarget' method. @@ -117,6 +111,9 @@ protected: Node *_target; /** The action tag. An identifier of the action */ int _tag; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Action); }; /** @@ -131,17 +128,6 @@ protected: class CC_DLL FiniteTimeAction : public Action { public: - /** - * @js ctor - */ - FiniteTimeAction() - : _duration(0) - {} - /** - * @js NA - * @lua NA - */ - virtual ~FiniteTimeAction(){} //! get duration in seconds of the action inline float getDuration() const { return _duration; } //! set duration in seconds of the action @@ -154,8 +140,16 @@ public: virtual FiniteTimeAction* clone() const override = 0; protected: + FiniteTimeAction() + : _duration(0) + {} + virtual ~FiniteTimeAction(){} + //! duration in seconds float _duration; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FiniteTimeAction); }; class ActionInterval; @@ -172,22 +166,11 @@ class CC_DLL Speed : public Action public: /** create the action */ static Speed* create(ActionInterval* action, float speed); - /** - * @js ctor - */ - Speed(); - /** - * @js NA - * @lua NA - */ - virtual ~Speed(void); inline float getSpeed(void) const { return _speed; } /** alter the speed of the inner function in runtime */ inline void setSpeed(float speed) { _speed = speed; } - /** initializes the action */ - bool initWithAction(ActionInterval *action, float speed); void setInnerAction(ActionInterval *action); @@ -204,8 +187,16 @@ public: virtual bool isDone() const override; protected: + Speed(); + virtual ~Speed(void); + /** initializes the action */ + bool initWithAction(ActionInterval *action, float speed); + float _speed; ActionInterval *_innerAction; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Speed); }; /** @@ -230,38 +221,11 @@ public: * with no boundary. */ static Follow* create(Node *followedNode, const Rect& rect = Rect::ZERO); - /** - * @js ctor - */ - Follow() - : _followedNode(nullptr) - , _boundarySet(false) - , _boundaryFullyCovered(false) - , _leftBoundary(0.0) - , _rightBoundary(0.0) - , _topBoundary(0.0) - , _bottomBoundary(0.0) - , _worldRect(Rect::ZERO) - {} - /** - * @js NA - * @lua NA - */ - virtual ~Follow(); - + inline bool isBoundarySet() const { return _boundarySet; } /** alter behavior - turn on/off boundary */ inline void setBoudarySet(bool value) { _boundarySet = value; } - /** - * Initializes the action with a set boundary or with no boundary. - * - * @param followedNode The node to be followed. - * @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work - * with no boundary. - */ - bool initWithTarget(Node *followedNode, const Rect& rect = Rect::ZERO); - // // Override // @@ -272,6 +236,33 @@ public: virtual void stop() override; protected: + /** + * @js ctor + */ + Follow() + : _followedNode(nullptr) + , _boundarySet(false) + , _boundaryFullyCovered(false) + , _leftBoundary(0.0) + , _rightBoundary(0.0) + , _topBoundary(0.0) + , _bottomBoundary(0.0) + , _worldRect(Rect::ZERO) + {} + /** + * @js NA + * @lua NA + */ + virtual ~Follow(); + /** + * Initializes the action with a set boundary or with no boundary. + * + * @param followedNode The node to be followed. + * @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work + * with no boundary. + */ + bool initWithTarget(Node *followedNode, const Rect& rect = Rect::ZERO); + // node to follow Node *_followedNode; @@ -292,6 +283,8 @@ protected: float _bottomBoundary; Rect _worldRect; +private: + CC_DISALLOW_COPY_AND_ASSIGN(Follow); }; // end of actions group diff --git a/cocos/2d/CCActionEase.h b/cocos/2d/CCActionEase.h index 13b708203a..efe0c9600c 100644 --- a/cocos/2d/CCActionEase.h +++ b/cocos/2d/CCActionEase.h @@ -44,14 +44,6 @@ class Object; class CC_DLL ActionEase : public ActionInterval { public: - /** - * @js NA - * @lua NA - */ - virtual ~ActionEase(void); - - /** initializes the action */ - bool initWithAction(ActionInterval *action); virtual ActionInterval* getInnerAction(); @@ -65,8 +57,16 @@ public: virtual void update(float time) override; protected: + ActionEase() {} + virtual ~ActionEase(); + /** initializes the action */ + bool initWithAction(ActionInterval *action); + /** The inner action */ ActionInterval *_inner; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ActionEase); }; /** @@ -76,15 +76,6 @@ protected: class CC_DLL EaseRateAction : public ActionEase { public: - /** - * @js NA - * @lua NA - */ - virtual ~EaseRateAction(); - - /** Initializes the action with the inner action and the rate parameter */ - bool initWithAction(ActionInterval *pAction, float fRate); - /** set rate value for the actions */ inline void setRate(float rate) { _rate = rate; } /** get rate value for the actions */ @@ -97,7 +88,15 @@ public: virtual EaseRateAction* reverse() const override = 0; protected: + EaseRateAction() {} + virtual ~EaseRateAction(); + /** Initializes the action with the inner action and the rate parameter */ + bool initWithAction(ActionInterval *pAction, float fRate); + float _rate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseRateAction); }; /** @@ -114,6 +113,13 @@ public: virtual void update(float time) override; virtual EaseIn* clone() const override; virtual EaseIn* reverse() const override; + +protected: + EaseIn() {} + virtual ~EaseIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseIn); }; /** @@ -130,6 +136,13 @@ public: virtual void update(float time) override; virtual EaseOut* clone() const override; virtual EaseOut* reverse() const override; + +protected: + EaseOut() {} + virtual ~EaseOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseOut); }; /** @@ -146,6 +159,13 @@ public: virtual void update(float time) override; virtual EaseInOut* clone() const override; virtual EaseInOut* reverse() const override; + +protected: + EaseInOut() {} + virtual ~EaseInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseInOut); }; /** @@ -162,6 +182,13 @@ public: virtual void update(float time) override; virtual EaseExponentialIn* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseExponentialIn() {} + virtual ~EaseExponentialIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseExponentialIn); }; /** @@ -178,6 +205,13 @@ public: virtual void update(float time) override; virtual EaseExponentialOut* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseExponentialOut() {} + virtual ~EaseExponentialOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseExponentialOut); }; /** @@ -194,6 +228,13 @@ public: virtual void update(float time) override; virtual EaseExponentialInOut* clone() const override; virtual EaseExponentialInOut* reverse() const override; + +protected: + EaseExponentialInOut() {} + virtual ~EaseExponentialInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseExponentialInOut); }; /** @@ -210,6 +251,13 @@ public: virtual void update(float time) override; virtual EaseSineIn* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseSineIn() {} + virtual ~EaseSineIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseSineIn); }; /** @@ -226,6 +274,13 @@ public: virtual void update(float time) override; virtual EaseSineOut* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseSineOut() {} + virtual ~EaseSineOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseSineOut); }; /** @@ -242,6 +297,13 @@ public: virtual void update(float time) override; virtual EaseSineInOut* clone() const override; virtual EaseSineInOut* reverse() const override; + +protected: + EaseSineInOut() {} + virtual ~EaseSineInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseSineInOut); }; /** @@ -252,8 +314,6 @@ public: class CC_DLL EaseElastic : public ActionEase { public: - /** Initializes the action with the inner action and the period in radians (default is 0.3) */ - bool initWithAction(ActionInterval *action, float period = 0.3f); /** get period of the wave in radians. default is 0.3 */ inline float getPeriod() const { return _period; } @@ -267,7 +327,16 @@ public: virtual EaseElastic* reverse() const override = 0; protected: + EaseElastic() {} + virtual ~EaseElastic() {} + /** Initializes the action with the inner action and the period in radians (default is 0.3) */ + bool initWithAction(ActionInterval *action, float period = 0.3f); + float _period; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseElastic); + }; /** @@ -287,6 +356,13 @@ public: virtual void update(float time) override; virtual EaseElasticIn* clone() const override; virtual EaseElastic* reverse() const override; + +protected: + EaseElasticIn() {} + virtual ~EaseElasticIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseElasticIn); }; /** @@ -306,6 +382,13 @@ public: virtual void update(float time) override; virtual EaseElasticOut* clone() const override; virtual EaseElastic* reverse() const override; + +protected: + EaseElasticOut() {} + virtual ~EaseElasticOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseElasticOut); }; /** @@ -325,6 +408,13 @@ public: virtual void update(float time) override; virtual EaseElasticInOut* clone() const override; virtual EaseElasticInOut* reverse() const override; + +protected: + EaseElasticInOut() {} + virtual ~EaseElasticInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseElasticInOut); }; /** @@ -340,6 +430,13 @@ public: // Overrides virtual EaseBounce* clone() const override = 0; virtual EaseBounce* reverse() const override = 0; + +protected: + EaseBounce() {} + virtual ~EaseBounce() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBounce); }; /** @@ -358,6 +455,13 @@ public: virtual void update(float time) override; virtual EaseBounceIn* clone() const override; virtual EaseBounce* reverse() const override; + +protected: + EaseBounceIn() {} + virtual ~EaseBounceIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBounceIn); }; /** @@ -376,6 +480,13 @@ public: virtual void update(float time) override; virtual EaseBounceOut* clone() const override; virtual EaseBounce* reverse() const override; + +protected: + EaseBounceOut() {} + virtual ~EaseBounceOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBounceOut); }; /** @@ -394,6 +505,13 @@ public: virtual void update(float time) override; virtual EaseBounceInOut* clone() const override; virtual EaseBounceInOut* reverse() const override; + +protected: + EaseBounceInOut() {} + virtual ~EaseBounceInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBounceInOut); }; /** @@ -412,6 +530,13 @@ public: virtual void update(float time) override; virtual EaseBackIn* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseBackIn() {} + virtual ~EaseBackIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBackIn); }; /** @@ -430,6 +555,13 @@ public: virtual void update(float time) override; virtual EaseBackOut* clone() const override; virtual ActionEase* reverse() const override; + +protected: + EaseBackOut() {} + virtual ~EaseBackOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBackOut); }; /** @@ -448,6 +580,13 @@ public: virtual void update(float time) override; virtual EaseBackInOut* clone() const override; virtual EaseBackInOut* reverse() const override; + +protected: + EaseBackInOut() {} + virtual ~EaseBackInOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(EaseBackInOut); }; // end of actions group diff --git a/cocos/2d/CCActionInstant.h b/cocos/2d/CCActionInstant.h index 01a26a3786..ad4c0ea314 100644 --- a/cocos/2d/CCActionInstant.h +++ b/cocos/2d/CCActionInstant.h @@ -65,7 +65,6 @@ public: /** Allocates and initializes the action */ static Show * create(); - Show(){} // // Overrides @@ -73,6 +72,13 @@ public: virtual void update(float time) override; virtual ActionInstant* reverse() const override; virtual Show* clone() const override; + +protected: + Show(){} + virtual ~Show(){} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Show); }; /** @@ -84,14 +90,19 @@ public: /** Allocates and initializes the action */ static Hide * create(); - Hide(){} - // // Overrides // virtual void update(float time) override; virtual ActionInstant* reverse() const override; virtual Hide* clone() const override; + +protected: + Hide(){} + virtual ~Hide(){} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Hide); }; /** @brief Toggles the visibility of a node @@ -102,14 +113,19 @@ public: /** Allocates and initializes the action */ static ToggleVisibility * create(); - ToggleVisibility(){} - // // Overrides // virtual void update(float time) override; virtual ToggleVisibility* reverse() const override; virtual ToggleVisibility* clone() const override; + +protected: + ToggleVisibility(){} + virtual ~ToggleVisibility(){} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ToggleVisibility); }; /** @@ -121,12 +137,6 @@ public: /** create the action */ static RemoveSelf * create(bool isNeedCleanUp = true); - RemoveSelf():_isNeedCleanUp(true) - {} - - /** init the action */ - bool init(bool isNeedCleanUp); - // // Override // @@ -135,7 +145,15 @@ public: virtual RemoveSelf* reverse() const override; protected: + RemoveSelf() : _isNeedCleanUp(true){} + virtual ~RemoveSelf(){} + /** init the action */ + bool init(bool isNeedCleanUp); + bool _isNeedCleanUp; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(RemoveSelf); }; /** @@ -148,13 +166,6 @@ public: /** create the action */ static FlipX * create(bool x); - FlipX() - :_flipX(false) - {} - - /** init the action */ - bool initWithFlipX(bool x); - // // Overrides // @@ -163,7 +174,15 @@ public: virtual FlipX* clone() const override; protected: + FlipX() :_flipX(false) {} + virtual ~FlipX() {} + /** init the action */ + bool initWithFlipX(bool x); + bool _flipX; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FlipX); }; /** @@ -176,13 +195,6 @@ public: /** create the action */ static FlipY * create(bool y); - FlipY() - :_flipY(false) - {} - - /** init the action */ - bool initWithFlipY(bool y); - // // Overrides // @@ -191,7 +203,15 @@ public: virtual FlipY* clone() const override; protected: + FlipY() :_flipY(false) {} + virtual ~FlipY() {} + /** init the action */ + bool initWithFlipY(bool y); + bool _flipY; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FlipY); }; /** @brief Places the node in a certain position @@ -199,12 +219,9 @@ protected: class CC_DLL Place : public ActionInstant // { public: - Place(){} /** creates a Place action with a position */ static Place * create(const Point& pos); - /** Initializes a Place action with a position */ - bool initWithPosition(const Point& pos); // // Overrides @@ -214,7 +231,15 @@ public: virtual Place* clone() const override; protected: + Place(){} + virtual ~Place(){} + /** Initializes a Place action with a position */ + bool initWithPosition(const Point& pos); + Point _position; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Place); }; @@ -240,34 +265,6 @@ public: */ CC_DEPRECATED_ATTRIBUTE static CallFunc * create(Object* target, SEL_CallFunc selector); -public: - /** - * @js ctor - */ - CallFunc() - : _selectorTarget(NULL) - , _callFunc(NULL) - , _function(nullptr) - { - } - /** - * @js NA - * @lua NA - */ - virtual ~CallFunc(); - - /** initializes the action with the callback - typedef void (Object::*SEL_CallFunc)(); - @deprecated Use the std::function API instead. - */ - CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target); - - /** initializes the action with the std::function - * @js NK - * @lua NK - */ - bool initWithFunction(const std::function& func); - /** executes the callback */ virtual void execute(); @@ -293,6 +290,25 @@ public: virtual CallFunc* clone() const override; protected: + CallFunc() + : _selectorTarget(NULL) + , _callFunc(NULL) + , _function(nullptr) + {} + virtual ~CallFunc(); + + /** initializes the action with the callback + typedef void (Object::*SEL_CallFunc)(); + @deprecated Use the std::function API instead. + */ + CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target); + + /** initializes the action with the std::function + * @js NK + * @lua NK + */ + bool initWithFunction(const std::function& func); + /** Target that will be called */ Object* _selectorTarget; @@ -304,6 +320,9 @@ protected: /** function that will be called */ std::function _function; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(CallFunc); }; /** @@ -324,19 +343,6 @@ public: @deprecated Use the std::function API instead. */ CC_DEPRECATED_ATTRIBUTE static CallFuncN * create(Object* target, SEL_CallFuncN selector); -public: - CallFuncN():_functionN(nullptr){} - - /** initializes the action with the std::function - */ - bool initWithFunction(const std::function& func); - - /** initializes the action with the callback - - typedef void (Object::*SEL_CallFuncN)(Node*); - @deprecated Use the std::function API instead. - */ - CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target, SEL_CallFuncN selector); // // Overrides @@ -345,8 +351,24 @@ public: virtual void execute() override; protected: + CallFuncN():_functionN(nullptr){} + virtual ~CallFuncN(){} + /** initializes the action with the std::function */ + bool initWithFunction(const std::function& func); + + /** initializes the action with the callback + + typedef void (Object::*SEL_CallFuncN)(Node*); + @deprecated Use the std::function API instead. + */ + CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target, SEL_CallFuncN selector); + + /** function that will be called with the "sender" as the 1st argument */ std::function _functionN; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(CallFuncN); }; /** @@ -361,11 +383,6 @@ public: /** creates the action with the callback and the data to pass as an argument */ CC_DEPRECATED_ATTRIBUTE static __CCCallFuncND * create(Object* target, SEL_CallFuncND selector, void* d); -protected: - /** initializes the action with the callback and the data to pass as an argument */ - bool initWithTarget(Object* target, SEL_CallFuncND selector, void* d); - -public: // // Overrides // @@ -373,8 +390,17 @@ public: virtual void execute() override; protected: + __CCCallFuncND() {} + virtual ~__CCCallFuncND() {} + + /** initializes the action with the callback and the data to pass as an argument */ + bool initWithTarget(Object* target, SEL_CallFuncND selector, void* d); + SEL_CallFuncND _callFuncND; void* _data; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(__CCCallFuncND); }; @@ -393,24 +419,6 @@ public: typedef void (Object::*SEL_CallFuncO)(Object*); */ CC_DEPRECATED_ATTRIBUTE static __CCCallFuncO * create(Object* target, SEL_CallFuncO selector, Object* object); - /** - * @js ctor - */ - __CCCallFuncO(); - /** - * @js NA - * @lua NA - */ - virtual ~__CCCallFuncO(); - -protected: - /** initializes the action with the callback - - typedef void (Object::*SEL_CallFuncO)(Object*); - */ - bool initWithTarget(Object* target, SEL_CallFuncO selector, Object* object); - -public: // // Overrides // @@ -421,9 +429,21 @@ public: void setObject(Object* obj); protected: + __CCCallFuncO(); + virtual ~__CCCallFuncO(); + /** initializes the action with the callback + + typedef void (Object::*SEL_CallFuncO)(Object*); + */ + bool initWithTarget(Object* target, SEL_CallFuncO selector, Object* object); + + /** object to be passed as argument */ Object* _object; SEL_CallFuncO _callFuncO; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(__CCCallFuncO); }; // end of actions group diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index bd300f73f0..a2ae6b7824 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -149,13 +149,13 @@ void ActionInterval::startWithTarget(Node *target) // Sequence // -Sequence* Sequence::createWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo) +Sequence* Sequence::createWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo) { - Sequence *pSequence = new Sequence(); - pSequence->initWithTwoActions(pActionOne, pActionTwo); - pSequence->autorelease(); + Sequence *sequence = new Sequence(); + sequence->initWithTwoActions(actionOne, actionTwo); + sequence->autorelease(); - return pSequence; + return sequence; } Sequence* Sequence::create(FiniteTimeAction *pAction1, ...) @@ -597,13 +597,13 @@ Spawn* Spawn::create(Array *arrayOfActions) return pRet; } -Spawn* Spawn::createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2) +Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2) { - Spawn *pSpawn = new Spawn(); - pSpawn->initWithTwoActions(pAction1, pAction2); - pSpawn->autorelease(); + Spawn *spawn = new Spawn(); + spawn->initWithTwoActions(action1, action2); + spawn->autorelease(); - return pSpawn; + return spawn; } bool Spawn:: initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2) diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index 270dca3414..a72327e997 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -64,9 +64,6 @@ public: /** how many seconds had elapsed since the actions started to run. */ inline float getElapsed(void) { return _elapsed; } - /** initializes the action */ - bool initWithDuration(float d); - //extension in GridAction void setAmplitudeRate(float amp); float getAmplitudeRate(void); @@ -80,8 +77,10 @@ public: virtual ActionInterval* reverse() const override = 0; virtual ActionInterval *clone() const override = 0; - protected: + /** initializes the action */ + bool initWithDuration(float d); + float _elapsed; bool _firstTick; }; @@ -105,14 +104,6 @@ public: static Sequence* createWithVariableList(FiniteTimeAction *pAction1, va_list args); /** creates the action */ static Sequence* createWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo); - /** - * @js NA - * @lua NA - */ - virtual ~Sequence(void); - - /** initializes the action */ - bool initWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo); // // Overrides @@ -124,9 +115,17 @@ public: virtual void update(float t) override; protected: + Sequence() {} + virtual ~Sequence(void); + /** initializes the action */ + bool initWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo); + FiniteTimeAction *_actions[2]; float _split; int _last; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Sequence); }; /** @brief Repeats an action a number of times. @@ -137,14 +136,6 @@ class CC_DLL Repeat : public ActionInterval public: /** creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */ static Repeat* create(FiniteTimeAction *pAction, unsigned int times); - /** - * @js NA - * @lua NA - */ - virtual ~Repeat(void); - - /** initializes a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */ - bool initWithAction(FiniteTimeAction *pAction, unsigned int times); inline void setInnerAction(FiniteTimeAction *pAction) { @@ -172,12 +163,20 @@ public: virtual bool isDone(void) const override; protected: + Repeat() {} + virtual ~Repeat(); + /** initializes a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */ + bool initWithAction(FiniteTimeAction *pAction, unsigned int times); + unsigned int _times; unsigned int _total; float _nextDt; bool _actionInstant; /** Inner action */ FiniteTimeAction *_innerAction; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Repeat); }; /** @brief Repeats an action for ever. @@ -189,20 +188,6 @@ class CC_DLL RepeatForever : public ActionInterval public: /** creates the action */ static RepeatForever* create(ActionInterval *pAction); - /** - * @js ctor - */ - RepeatForever() - : _innerAction(NULL) - {} - /** - * @js NA - * @lua NA - */ - virtual ~RepeatForever(); - - /** initializes the action */ - bool initWithAction(ActionInterval *pAction); inline void setInnerAction(ActionInterval *pAction) { @@ -229,8 +214,18 @@ public: virtual bool isDone(void) const override; protected: + RepeatForever() + : _innerAction(nullptr) + {} + virtual ~RepeatForever(); + /** initializes the action */ + bool initWithAction(ActionInterval *pAction); + /** Inner action */ ActionInterval *_innerAction; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(RepeatForever); }; /** @brief Spawn a new action immediately @@ -255,14 +250,6 @@ public: /** creates the Spawn action */ static Spawn* createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); - /** - * @js NA - * @lua NA - */ - virtual ~Spawn(void); - - /** initializes the Spawn action with the 2 actions to spawn */ - bool initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); // // Overrides @@ -274,8 +261,16 @@ public: virtual void update(float time) override; protected: + Spawn() {} + virtual ~Spawn(); + /** initializes the Spawn action with the 2 actions to spawn */ + bool initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); + FiniteTimeAction *_one; FiniteTimeAction *_two; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Spawn); }; /** @brief Rotates a Node object to a certain angle by modifying it's @@ -290,10 +285,6 @@ public: /** creates the action */ static RotateTo* create(float fDuration, float fDeltaAngle); - /** initializes the action */ - bool initWithDuration(float fDuration, float fDeltaAngle); - - bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); // // Overrides @@ -304,6 +295,12 @@ public: virtual void update(float time) override; protected: + RotateTo() {} + virtual ~RotateTo() {} + /** initializes the action */ + bool initWithDuration(float fDuration, float fDeltaAngle); + bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + float _dstAngleX; float _startAngleX; float _diffAngleX; @@ -311,6 +308,9 @@ protected: float _dstAngleY; float _startAngleY; float _diffAngleY; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(RotateTo); }; /** @brief Rotates a Node object clockwise a number of degrees by modifying it's rotation attribute. @@ -320,12 +320,7 @@ class CC_DLL RotateBy : public ActionInterval public: /** creates the action */ static RotateBy* create(float fDuration, float fDeltaAngle); - - /** initializes the action */ - bool initWithDuration(float fDuration, float fDeltaAngle); - static RotateBy* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY); - bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); // // Override @@ -336,10 +331,19 @@ public: virtual void update(float time) override; protected: + RotateBy() {} + virtual ~RotateBy() {} + /** initializes the action */ + bool initWithDuration(float fDuration, float fDeltaAngle); + bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); + float _angleX; float _startAngleX; float _angleY; float _startAngleY; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(RotateBy); }; /** Moves a Node object x,y pixels by modifying it's position attribute. @@ -354,9 +358,6 @@ public: /** creates the action */ static MoveBy* create(float duration, const Point& deltaPosition); - /** initializes the action */ - bool initWithDuration(float duration, const Point& deltaPosition); - // // Overrides // @@ -366,9 +367,17 @@ public: virtual void update(float time) override; protected: + MoveBy() {} + virtual ~MoveBy() {} + /** initializes the action */ + bool initWithDuration(float duration, const Point& deltaPosition); + Point _positionDelta; Point _startPosition; Point _previousPosition; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MoveBy); }; /** Moves a Node object to the position x,y. x and y are absolute coordinates by modifying it's position attribute. @@ -382,9 +391,6 @@ public: /** creates the action */ static MoveTo* create(float duration, const Point& position); - /** initializes the action */ - bool initWithDuration(float duration, const Point& position); - // // Overrides // @@ -392,7 +398,15 @@ public: virtual void startWithTarget(Node *target) override; protected: + MoveTo() {} + virtual ~MoveTo() {} + /** initializes the action */ + bool initWithDuration(float duration, const Point& position); + Point _endPosition; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(MoveTo); }; /** Skews a Node object to given angles by modifying it's skewX and skewY attributes @@ -404,9 +418,6 @@ public: /** creates the action */ static SkewTo* create(float t, float sx, float sy); - SkewTo(); - bool initWithDuration(float t, float sx, float sy); - // // Overrides // @@ -416,6 +427,10 @@ public: virtual void update(float time) override; protected: + SkewTo(); + virtual ~SkewTo() {} + bool initWithDuration(float t, float sx, float sy); + float _skewX; float _skewY; float _startSkewX; @@ -424,6 +439,9 @@ protected: float _endSkewY; float _deltaX; float _deltaY; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(SkewTo); }; /** Skews a Node object by skewX and skewY degrees @@ -435,14 +453,20 @@ public: /** creates the action */ static SkewBy* create(float t, float deltaSkewX, float deltaSkewY); - bool initWithDuration(float t, float sx, float sy); - // // Overrides // virtual void startWithTarget(Node *target) override; virtual SkewBy* clone() const override; virtual SkewBy* reverse(void) const override; + +protected: + SkewBy() {} + virtual ~SkewBy() {} + bool initWithDuration(float t, float sx, float sy); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(SkewBy); }; /** @brief Moves a Node object simulating a parabolic jump movement by modifying it's position attribute. @@ -453,9 +477,6 @@ public: /** creates the action */ static JumpBy* create(float duration, const Point& position, float height, int jumps); - /** initializes the action */ - bool initWithDuration(float duration, const Point& position, float height, int jumps); - // // Overrides // @@ -465,11 +486,19 @@ public: virtual void update(float time) override; protected: + JumpBy() {} + virtual ~JumpBy() {} + /** initializes the action */ + bool initWithDuration(float duration, const Point& position, float height, int jumps); + Point _startPosition; Point _delta; float _height; int _jumps; Point _previousPos; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(JumpBy); }; /** @brief Moves a Node object to a parabolic position simulating a jump movement by modifying it's position attribute. @@ -486,6 +515,11 @@ public: virtual void startWithTarget(Node *target) override; virtual JumpTo* clone() const override; virtual JumpTo* reverse(void) const override; + +private: + JumpTo() {} + virtual ~JumpTo() {} + CC_DISALLOW_COPY_AND_ASSIGN(JumpTo); }; /** Bezier configuration structure @@ -513,9 +547,6 @@ public: */ static BezierBy* create(float t, const ccBezierConfig& c); - /** initializes the action with a duration and a bezier configuration */ - bool initWithDuration(float t, const ccBezierConfig& c); - // // Overrides // @@ -525,9 +556,17 @@ public: virtual void update(float time) override; protected: + BezierBy() {} + virtual ~BezierBy() {} + /** initializes the action with a duration and a bezier configuration */ + bool initWithDuration(float t, const ccBezierConfig& c); + ccBezierConfig _config; Point _startPosition; Point _previousPosition; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(BezierBy); }; /** @brief An action that moves the target with a cubic Bezier curve to a destination point. @@ -544,7 +583,6 @@ public: * @endcode */ static BezierTo* create(float t, const ccBezierConfig& c); - bool initWithDuration(float t, const ccBezierConfig &c); // // Overrides @@ -554,7 +592,14 @@ public: virtual BezierTo* reverse(void) const override; protected: + BezierTo() {} + virtual ~BezierTo() {} + bool initWithDuration(float t, const ccBezierConfig &c); + ccBezierConfig _toConfig; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(BezierTo); }; /** @brief Scales a Node object to a zoom factor by modifying it's scale attribute. @@ -569,12 +614,6 @@ public: /** creates the action with and X factor and a Y factor */ static ScaleTo* create(float duration, float sx, float sy); - /** initializes the action with the same scale factor for X and Y */ - bool initWithDuration(float duration, float s); - - /** initializes the action with and X factor and a Y factor */ - bool initWithDuration(float duration, float sx, float sy); - // // Overrides // @@ -584,6 +623,13 @@ public: virtual void update(float time) override; protected: + ScaleTo() {} + virtual ~ScaleTo() {} + /** initializes the action with the same scale factor for X and Y */ + bool initWithDuration(float duration, float s); + /** initializes the action with and X factor and a Y factor */ + bool initWithDuration(float duration, float sx, float sy); + float _scaleX; float _scaleY; float _startScaleX; @@ -592,6 +638,9 @@ protected: float _endScaleY; float _deltaX; float _deltaY; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ScaleTo); }; /** @brief Scales a Node object a zoom factor by modifying it's scale attribute. @@ -611,6 +660,13 @@ public: virtual void startWithTarget(Node *target) override; virtual ScaleBy* clone() const override; virtual ScaleBy* reverse(void) const override; + +protected: + ScaleBy() {} + virtual ~ScaleBy() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ScaleBy); }; /** @brief Blinks a Node object by modifying it's visible attribute @@ -621,9 +677,6 @@ public: /** creates the action */ static Blink* create(float duration, int blinks); - /** initializes the action */ - bool initWithDuration(float duration, int blinks); - // // Overrides // @@ -634,8 +687,16 @@ public: virtual void stop() override; protected: + Blink() {} + virtual ~Blink() {} + /** initializes the action */ + bool initWithDuration(float duration, int blinks); + int _times; bool _originalState; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Blink); }; /** @brief Fades In an object that implements the RGBAProtocol protocol. It modifies the opacity from 0 to 255. @@ -653,6 +714,13 @@ public: virtual void update(float time) override; virtual FadeIn* clone() const override; virtual ActionInterval* reverse(void) const override; + +protected: + FadeIn() {} + virtual ~FadeIn() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeIn); }; /** @brief Fades Out an object that implements the RGBAProtocol protocol. It modifies the opacity from 255 to 0. @@ -670,6 +738,13 @@ public: virtual void update(float time) override; virtual FadeOut* clone() const override; virtual ActionInterval* reverse(void) const override; + +protected: + FadeOut() {} + virtual ~FadeOut() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeOut); }; /** @brief Fades an object that implements the RGBAProtocol protocol. It modifies the opacity from the current value to a custom one. @@ -681,9 +756,6 @@ public: /** creates an action with duration and opacity */ static FadeTo* create(float duration, GLubyte opacity); - /** initializes the action with duration and opacity */ - bool initWithDuration(float duration, GLubyte opacity); - // // Overrides // @@ -693,8 +765,16 @@ public: virtual void update(float time) override; protected: + FadeTo() {} + virtual ~FadeTo() {} + /** initializes the action with duration and opacity */ + bool initWithDuration(float duration, GLubyte opacity); + GLubyte _toOpacity; GLubyte _fromOpacity; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeTo); }; /** @brief Tints a Node that implements the NodeRGB protocol from current tint to a custom one. @@ -707,9 +787,6 @@ public: /** creates an action with duration and color */ static TintTo* create(float duration, GLubyte red, GLubyte green, GLubyte blue); - /** initializes the action with duration and color */ - bool initWithDuration(float duration, GLubyte red, GLubyte green, GLubyte blue); - // // Overrides // @@ -719,8 +796,16 @@ public: virtual void update(float time) override; protected: + TintTo() {} + virtual ~TintTo() {} + /** initializes the action with duration and color */ + bool initWithDuration(float duration, GLubyte red, GLubyte green, GLubyte blue); + Color3B _to; Color3B _from; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TintTo); }; /** @brief Tints a Node that implements the NodeRGB protocol from current tint to a custom one. @@ -732,9 +817,6 @@ public: /** creates an action with duration and color */ static TintBy* create(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue); - /** initializes the action with duration and color */ - bool initWithDuration(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue); - // // Overrides // @@ -744,6 +826,11 @@ public: virtual void update(float time) override; protected: + TintBy() {} + virtual ~TintBy() {} + /** initializes the action with duration and color */ + bool initWithDuration(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue); + GLshort _deltaR; GLshort _deltaG; GLshort _deltaB; @@ -751,6 +838,9 @@ protected: GLshort _fromR; GLshort _fromG; GLshort _fromB; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TintBy); }; /** @brief Delays the action a certain amount of seconds @@ -767,6 +857,13 @@ public: virtual void update(float time) override; virtual DelayTime* reverse() const override; virtual DelayTime* clone() const override; + +protected: + DelayTime() {} + virtual ~DelayTime() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(DelayTime); }; /** @brief Executes an action in reverse order, from time=duration to time=0 @@ -781,18 +878,6 @@ class CC_DLL ReverseTime : public ActionInterval public: /** creates the action */ static ReverseTime* create(FiniteTimeAction *pAction); - /** - * @js NA - * @lua NA - */ - virtual ~ReverseTime(void); - /** - * @js ctor - */ - ReverseTime(); - - /** initializes the action */ - bool initWithAction(FiniteTimeAction *pAction); // // Overrides @@ -804,7 +889,15 @@ public: virtual void update(float time) override; protected: + ReverseTime(); + virtual ~ReverseTime(void); + /** initializes the action */ + bool initWithAction(FiniteTimeAction *pAction); + FiniteTimeAction *_other; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ReverseTime); }; class Texture2D; @@ -814,18 +907,6 @@ class CC_DLL Animate : public ActionInterval public: /** creates the action with an Animation and will restore the original frame when the animation is over */ static Animate* create(Animation *pAnimation); - /** - * @js ctor - */ - Animate(); - /** - * @js NA - * @lua NA - */ - virtual ~Animate(); - - /** initializes the action with an Animation and will restore the original frame when the animation is over */ - bool initWithAnimation(Animation *pAnimation); /** sets the Animation object to be animated */ void setAnimation( Animation* animation ); @@ -843,11 +924,19 @@ public: virtual void update(float t) override; protected: + Animate(); + virtual ~Animate(); + /** initializes the action with an Animation and will restore the original frame when the animation is over */ + bool initWithAnimation(Animation *pAnimation); + std::vector* _splitTimes; int _nextFrame; SpriteFrame* _origFrame; unsigned int _executedLoops; Animation* _animation; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Animate); }; /** Overrides the target of an action so that it always runs on the target @@ -856,22 +945,9 @@ protected: class CC_DLL TargetedAction : public ActionInterval { public: - /** - * @js ctor - */ - TargetedAction(); - /** - * @js NA - * @lua NA - */ - virtual ~TargetedAction(); - /** Create an action with the specified action and forced target */ static TargetedAction* create(Node* target, FiniteTimeAction* pAction); - /** Init an action with the specified action and forced target */ - bool initWithTarget(Node* target, FiniteTimeAction* pAction); - /** Sets the target that the action will be forced to run with */ void setForcedTarget(Node* forcedTarget); /** returns the target that the action is forced to run with */ @@ -887,9 +963,17 @@ public: virtual void stop(void) override; virtual void update(float time) override; -private: +protected: + TargetedAction(); + virtual ~TargetedAction(); + /** Init an action with the specified action and forced target */ + bool initWithTarget(Node* target, FiniteTimeAction* pAction); + FiniteTimeAction* _action; Node* _forcedTarget; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TargetedAction); }; // end of actions group From 192deb7952a5ad783bf3d6d551c1db510de6e503 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Fri, 22 Nov 2013 11:51:07 +0800 Subject: [PATCH 16/75] issue #3228: Reconstruct the Callfunc create method to support std::function and add callFuncND + auto remove lua test case --- cocos/2d/CCActionInstant.cpp | 2 +- cocos/2d/CCActionInstant.h | 4 +- .../lua/bindings/LuaScriptHandlerMgr.cpp | 47 +++++++++++-------- .../lua/bindings/LuaScriptHandlerMgr.h | 12 +++-- .../lua_cocos2dx_manual.cpp.REMOVED.git-id | 2 +- .../luaScript/ActionsTest/ActionsTest.lua | 9 ++++ 6 files changed, 50 insertions(+), 26 deletions(-) diff --git a/cocos/2d/CCActionInstant.cpp b/cocos/2d/CCActionInstant.cpp index 8a862f5771..408a400e84 100644 --- a/cocos/2d/CCActionInstant.cpp +++ b/cocos/2d/CCActionInstant.cpp @@ -472,7 +472,7 @@ CallFuncN * CallFuncN::clone() const if( _selectorTarget) { a->initWithTarget(_selectorTarget, _callFuncN); } - else if( _function ){ + else if( _functionN ){ a->initWithFunction(_functionN); } diff --git a/cocos/2d/CCActionInstant.h b/cocos/2d/CCActionInstant.h index 01a26a3786..68ca323e2f 100644 --- a/cocos/2d/CCActionInstant.h +++ b/cocos/2d/CCActionInstant.h @@ -263,8 +263,8 @@ public: CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* target); /** initializes the action with the std::function - * @js NK - * @lua NK + * @js NA + * @lua NA */ bool initWithFunction(const std::function& func); diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp index ab4d01bd01..d627be2e18 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp @@ -48,31 +48,35 @@ void ScheduleHandlerDelegate::update(float elapse) } -LuaCallFunc * LuaCallFunc::create(int nHandler) +LuaCallFunc * LuaCallFunc::create(const std::function& func) { - LuaCallFunc *ret = new LuaCallFunc(); - if (NULL != ret ) - { + auto ret = new LuaCallFunc(); + + if (ret && ret->initWithFunction(func) ) { ret->autorelease(); - ScriptHandlerMgr::getInstance()->addObjectHandler((void*)ret, nHandler, ScriptHandlerMgr::HandlerType::CALLFUNC); return ret; } + + CC_SAFE_DELETE(ret); + return NULL; +} + +void LuaCallFunc::execute() +{ + if (_functionLua) + { + _functionLua((void*)this,_target); + } else { - CC_SAFE_DELETE(ret); - return NULL; + CallFuncN::execute(); } } -void LuaCallFunc::execute() + +bool LuaCallFunc::initWithFunction(const std::function &func) { - int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::CALLFUNC); - - if (0 == handler) - return ; - - BasicScriptData data((void*)this,(void*)_target); - ScriptEvent event(kCallFuncEvent,(void*)&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); + _functionLua = func; + return true; } LuaCallFunc* LuaCallFunc::clone() const @@ -83,13 +87,18 @@ LuaCallFunc* LuaCallFunc::clone() const return NULL; auto ret = new LuaCallFunc(); + + if( _functionLua ) + { + ret->initWithFunction(_functionLua); + } + + ret->autorelease(); int newscriptHandler = cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->reallocateScriptHandler(handler); ScriptHandlerMgr::getInstance()->addObjectHandler((void*)ret, newscriptHandler, ScriptHandlerMgr::HandlerType::CALLFUNC); - - ret->autorelease(); - + return ret; } diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h index 3d0acfc87e..8d567019e2 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h @@ -44,14 +44,20 @@ private: class LuaCallFunc:public cocos2d::CallFuncN { public: - LuaCallFunc() + LuaCallFunc():_functionLua(nullptr) {} virtual ~LuaCallFunc() {} - static LuaCallFunc * create(int nHandler); - virtual void execute(); + static LuaCallFunc* create(const std::function& func); + bool initWithFunction(const std::function& func); virtual LuaCallFunc* clone() const; + virtual void execute() override; +protected: + /** + */ + std::function _functionLua; + }; class ScriptHandlerMgr diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index c59adc5e90..c3dcf3390c 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -6f20ef3b233b2dffcfa11fe289879cfc5ee35d51 \ No newline at end of file +86fa141032de3d513df690fc82b20d2f2b4ab01b \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua b/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua index 52a3e5f892..414870acbb 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua @@ -835,6 +835,15 @@ local function ActionCallFuncND() centerSprites(1) + local function doRemoveFromParentAndCleanup(sender,table) + grossini:removeFromParentAndCleanup(table[1]) + end + + local action = cc.Sequence:create( + cc.MoveBy:create(2, cc.p(200,0)), + cc.CallFunc:create(doRemoveFromParentAndCleanup,{true})) + + grossini:runAction(action) Helper.titleLabel:setString("CallFuncND + auto remove") Helper.subtitleLabel:setString("CallFuncND + removeFromParent. Grossini dissapears in 2s") From 3a69ee301b973605c790d361a3fca0748ca50f82 Mon Sep 17 00:00:00 2001 From: samuele3 Date: Fri, 22 Nov 2013 14:06:48 +0800 Subject: [PATCH 17/75] issue #3228: Resolve TestLua and HelloLua test samples compile error on the Xcode 4.6.2 when choose Mac platform --- build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index fe0929b0b5..5d39134d33 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2461d13fd6f4fadc6ee396109932e50b1de8ed99 \ No newline at end of file +b343c033f369dd9a1cd41baf60012cd447af6970 \ No newline at end of file From 49a1d0ae6251a2d59df1bce6210e2774323ca735 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 22 Nov 2013 17:41:03 +0800 Subject: [PATCH 18/75] Remove something association of CDT Builder,it make 'miss error' in builders. --- .../AssetsManagerTest/proj.android/.cproject | 113 ----------------- .../Javah_jni_builder.launch | 11 -- .../AssetsManagerTest/proj.android/.project | 20 --- samples/Cpp/HelloCpp/proj.android/.cproject | 110 ----------------- .../Javah_jni_builder.launch | 11 -- samples/Cpp/HelloCpp/proj.android/.project | 20 --- samples/Cpp/SimpleGame/proj.android/.cproject | 110 ----------------- .../Javah_jni_builder.launch | 11 -- samples/Cpp/SimpleGame/proj.android/.project | 20 --- samples/Cpp/TestCpp/proj.android/.cproject | 112 ----------------- samples/Cpp/TestCpp/proj.android/.project | 10 -- .../CocosDragonJS/proj.android/.cproject | 114 ------------------ .../Javah_jni_builder.launch | 11 -- .../CocosDragonJS/proj.android/.project | 20 --- .../CrystalCraze/proj.android/.cproject | 114 ------------------ .../Javah_jni_builder.launch | 11 -- .../CrystalCraze/proj.android/.project | 20 --- .../MoonWarriors/proj.android/.cproject | 114 ------------------ .../Javah_jni_builder.launch | 11 -- .../MoonWarriors/proj.android/.project | 20 --- .../TestJavascript/proj.android/.cproject | 114 ------------------ .../Javah_jni_builder.launch | 11 -- .../TestJavascript/proj.android/.project | 20 --- .../WatermelonWithMe/proj.android/.cproject | 114 ------------------ .../Javah_jni_builder.launch | 11 -- .../WatermelonWithMe/proj.android/.project | 20 --- samples/Lua/HelloLua/proj.android/.cproject | 45 ------- samples/Lua/HelloLua/proj.android/.project | 10 -- samples/Lua/TestLua/proj.android/.cproject | 45 ------- samples/Lua/TestLua/proj.android/.project | 10 -- .../multi-platform-cpp/proj.android/.cproject | 111 ----------------- .../multi-platform-cpp/proj.android/.project | 10 -- .../multi-platform-js/proj.android/.cproject | 109 ----------------- .../multi-platform-js/proj.android/.project | 10 -- 34 files changed, 1623 deletions(-) delete mode 100644 samples/Cpp/AssetsManagerTest/proj.android/.cproject delete mode 100644 samples/Cpp/AssetsManagerTest/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Cpp/HelloCpp/proj.android/.cproject delete mode 100644 samples/Cpp/HelloCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Cpp/SimpleGame/proj.android/.cproject delete mode 100644 samples/Cpp/SimpleGame/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Cpp/TestCpp/proj.android/.cproject delete mode 100644 samples/Javascript/CocosDragonJS/proj.android/.cproject delete mode 100644 samples/Javascript/CocosDragonJS/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Javascript/CrystalCraze/proj.android/.cproject delete mode 100644 samples/Javascript/CrystalCraze/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Javascript/MoonWarriors/proj.android/.cproject delete mode 100644 samples/Javascript/MoonWarriors/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Javascript/TestJavascript/proj.android/.cproject delete mode 100644 samples/Javascript/TestJavascript/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Javascript/WatermelonWithMe/proj.android/.cproject delete mode 100644 samples/Javascript/WatermelonWithMe/proj.android/.externalToolBuilders/Javah_jni_builder.launch delete mode 100644 samples/Lua/HelloLua/proj.android/.cproject delete mode 100644 samples/Lua/TestLua/proj.android/.cproject delete mode 100644 template/multi-platform-cpp/proj.android/.cproject delete mode 100644 template/multi-platform-js/proj.android/.cproject diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.cproject b/samples/Cpp/AssetsManagerTest/proj.android/.cproject deleted file mode 100644 index 5dcf7dc84a..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/.cproject +++ /dev/null @@ -1,113 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Cpp/AssetsManagerTest/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.project b/samples/Cpp/AssetsManagerTest/proj.android/.project index 87fc1c9e0e..515077d245 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/.project +++ b/samples/Cpp/AssetsManagerTest/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Cpp/HelloCpp/proj.android/.cproject b/samples/Cpp/HelloCpp/proj.android/.cproject deleted file mode 100644 index dfee0913c6..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/.cproject +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/HelloCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Cpp/HelloCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Cpp/HelloCpp/proj.android/.project b/samples/Cpp/HelloCpp/proj.android/.project index 93335a6f16..908b979a53 100644 --- a/samples/Cpp/HelloCpp/proj.android/.project +++ b/samples/Cpp/HelloCpp/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (5).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Cpp/SimpleGame/proj.android/.cproject b/samples/Cpp/SimpleGame/proj.android/.cproject deleted file mode 100644 index dca6895dcf..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/.cproject +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/SimpleGame/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Cpp/SimpleGame/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Cpp/SimpleGame/proj.android/.project b/samples/Cpp/SimpleGame/proj.android/.project index 4e2c99e96f..bf3f3d0350 100644 --- a/samples/Cpp/SimpleGame/proj.android/.project +++ b/samples/Cpp/SimpleGame/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (8).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Cpp/TestCpp/proj.android/.cproject b/samples/Cpp/TestCpp/proj.android/.cproject deleted file mode 100644 index 5bcd6903c9..0000000000 --- a/samples/Cpp/TestCpp/proj.android/.cproject +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/TestCpp/proj.android/.project b/samples/Cpp/TestCpp/proj.android/.project index b02e99a830..dd5dee2a3b 100644 --- a/samples/Cpp/TestCpp/proj.android/.project +++ b/samples/Cpp/TestCpp/proj.android/.project @@ -20,16 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (9).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Javascript/CocosDragonJS/proj.android/.cproject b/samples/Javascript/CocosDragonJS/proj.android/.cproject deleted file mode 100644 index 22eaa79305..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CocosDragonJS/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Javascript/CocosDragonJS/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Javascript/CocosDragonJS/proj.android/.project b/samples/Javascript/CocosDragonJS/proj.android/.project index 0a89f1ca12..0a52fa2ab9 100644 --- a/samples/Javascript/CocosDragonJS/proj.android/.project +++ b/samples/Javascript/CocosDragonJS/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (3).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Javascript/CrystalCraze/proj.android/.cproject b/samples/Javascript/CrystalCraze/proj.android/.cproject deleted file mode 100644 index 3ddae34a8c..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Javascript/CrystalCraze/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/.project b/samples/Javascript/CrystalCraze/proj.android/.project index 274dcabae3..48f68239f6 100644 --- a/samples/Javascript/CrystalCraze/proj.android/.project +++ b/samples/Javascript/CrystalCraze/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (4).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Javascript/MoonWarriors/proj.android/.cproject b/samples/Javascript/MoonWarriors/proj.android/.cproject deleted file mode 100644 index 50b01bc715..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Javascript/MoonWarriors/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/.project b/samples/Javascript/MoonWarriors/proj.android/.project index 6c9a469ace..4bdf70520e 100644 --- a/samples/Javascript/MoonWarriors/proj.android/.project +++ b/samples/Javascript/MoonWarriors/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (7).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Javascript/TestJavascript/proj.android/.cproject b/samples/Javascript/TestJavascript/proj.android/.cproject deleted file mode 100644 index 072ccb5782..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/TestJavascript/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Javascript/TestJavascript/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Javascript/TestJavascript/proj.android/.project b/samples/Javascript/TestJavascript/proj.android/.project index 4474f112c9..48030971da 100644 --- a/samples/Javascript/TestJavascript/proj.android/.project +++ b/samples/Javascript/TestJavascript/proj.android/.project @@ -25,26 +25,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (10).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.cproject b/samples/Javascript/WatermelonWithMe/proj.android/.cproject deleted file mode 100644 index 46c27fc07d..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Javascript/WatermelonWithMe/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.project b/samples/Javascript/WatermelonWithMe/proj.android/.project index e6fddbb64c..1a3080f5bb 100644 --- a/samples/Javascript/WatermelonWithMe/proj.android/.project +++ b/samples/Javascript/WatermelonWithMe/proj.android/.project @@ -20,26 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/Javah_jni_builder.launch - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (12).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/samples/Lua/HelloLua/proj.android/.cproject b/samples/Lua/HelloLua/proj.android/.cproject deleted file mode 100644 index e9b9413992..0000000000 --- a/samples/Lua/HelloLua/proj.android/.cproject +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.android/.project b/samples/Lua/HelloLua/proj.android/.project index 633e8ba316..2a61577d0c 100644 --- a/samples/Lua/HelloLua/proj.android/.project +++ b/samples/Lua/HelloLua/proj.android/.project @@ -5,16 +5,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (6).launch - - - com.android.ide.eclipse.adt.ResourceManagerBuilder diff --git a/samples/Lua/TestLua/proj.android/.cproject b/samples/Lua/TestLua/proj.android/.cproject deleted file mode 100644 index e62561afc7..0000000000 --- a/samples/Lua/TestLua/proj.android/.cproject +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/TestLua/proj.android/.project b/samples/Lua/TestLua/proj.android/.project index 6c0b0be311..fac9edb71e 100644 --- a/samples/Lua/TestLua/proj.android/.project +++ b/samples/Lua/TestLua/proj.android/.project @@ -5,16 +5,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (11).launch - - - com.android.ide.eclipse.adt.ResourceManagerBuilder diff --git a/template/multi-platform-cpp/proj.android/.cproject b/template/multi-platform-cpp/proj.android/.cproject deleted file mode 100644 index 3514d06dd2..0000000000 --- a/template/multi-platform-cpp/proj.android/.cproject +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/template/multi-platform-cpp/proj.android/.project b/template/multi-platform-cpp/proj.android/.project index c07874533a..ca9146dc08 100644 --- a/template/multi-platform-cpp/proj.android/.project +++ b/template/multi-platform-cpp/proj.android/.project @@ -20,16 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder (1).launch - - - com.android.ide.eclipse.adt.ApkBuilder diff --git a/template/multi-platform-js/proj.android/.cproject b/template/multi-platform-js/proj.android/.cproject deleted file mode 100644 index 9ebba484ce..0000000000 --- a/template/multi-platform-js/proj.android/.cproject +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/template/multi-platform-js/proj.android/.project b/template/multi-platform-js/proj.android/.project index c65124f88e..df461895c5 100644 --- a/template/multi-platform-js/proj.android/.project +++ b/template/multi-platform-js/proj.android/.project @@ -20,16 +20,6 @@ - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch - - - com.android.ide.eclipse.adt.ApkBuilder From 4d7e56b44abefbdb1967f84a010e2fdd15d4b324 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 09:42:21 -0800 Subject: [PATCH 19/75] fix indentation --- cocos/2d/CCGLProgram.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCGLProgram.h b/cocos/2d/CCGLProgram.h index c7b6b2728c..2d66baf3bb 100644 --- a/cocos/2d/CCGLProgram.h +++ b/cocos/2d/CCGLProgram.h @@ -251,7 +251,7 @@ private: GLint _uniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; - struct flag_struct { + struct flag_struct { unsigned int usesTime:1; unsigned int usesMVP:1; unsigned int usesMV:1; From 1c65669a9f845977d1075a9f8c0b098726fd9291 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 11:27:03 -0800 Subject: [PATCH 20/75] fixes type in documentation --- samples/Cpp/TestCpp/Classes/testBasic.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index e47dcd24a0..013b5d8563 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -33,7 +33,7 @@ void TestScene::onEnter() /* ****** GCC Compiler issue on Android and Linux (CLANG compiler is ok) ****** We couldn't use 'Scene::create' directly since gcc will trigger - an error called "error: 'this' was not captured for this lambda function". + an error called "error: 'this' was not captured for this lambda function". This is because 'Scene' is the super class of TestScene, if we invoke 'Scene::create' directly in this lambda expression, gcc compiler found 'Scene::create' and it think that was the member function of 'TestScene' 's super class, but this lambda function doesn't From 3ab1e4f3a1ed012d04f77df447601b19cc13a8d5 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 12:15:41 -0800 Subject: [PATCH 21/75] ClippingNode Test works again --- .../ClippingNodeTest/ClippingNodeTest.cpp | 57 ++++++++----------- .../ConfigurationTest/ConfigurationTest.cpp | 18 ++---- .../Classes/FileUtilsTest/FileUtilsTest.cpp | 19 ++----- .../Classes/SchedulerTest/SchedulerTest.cpp | 51 ++++++----------- samples/Cpp/TestCpp/Classes/testBasic.h | 7 --- 5 files changed, 53 insertions(+), 99 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 84bbf9eb15..30e94367eb 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -16,36 +16,21 @@ enum { kTagContentNode = 102, }; -TESTLAYER_CREATE_FUNC(ScrollViewDemo); -TESTLAYER_CREATE_FUNC(HoleDemo); -TESTLAYER_CREATE_FUNC(ShapeTest); -TESTLAYER_CREATE_FUNC(ShapeInvertedTest); -TESTLAYER_CREATE_FUNC(SpriteTest); -TESTLAYER_CREATE_FUNC(SpriteNoAlphaTest); -TESTLAYER_CREATE_FUNC(SpriteInvertedTest); -TESTLAYER_CREATE_FUNC(NestedTest); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest2); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest3); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest4); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest5); -TESTLAYER_CREATE_FUNC(RawStencilBufferTest6); - -static NEWTESTFUNC createFunctions[] = { - CF(ScrollViewDemo), - CF(HoleDemo), - CF(ShapeTest), - CF(ShapeInvertedTest), - CF(SpriteTest), - CF(SpriteNoAlphaTest), - CF(SpriteInvertedTest), - CF(NestedTest), - CF(RawStencilBufferTest), - CF(RawStencilBufferTest2), - CF(RawStencilBufferTest3), - CF(RawStencilBufferTest4), - CF(RawStencilBufferTest5), - CF(RawStencilBufferTest6) +static std::function createFunctions[] = { + CL(ScrollViewDemo), + CL(HoleDemo), + CL(ShapeTest), + CL(ShapeInvertedTest), + CL(SpriteTest), + CL(SpriteNoAlphaTest), + CL(SpriteInvertedTest), + CL(NestedTest), + CL(RawStencilBufferTest), + CL(RawStencilBufferTest2), + CL(RawStencilBufferTest3), + CL(RawStencilBufferTest4), + CL(RawStencilBufferTest5), + CL(RawStencilBufferTest6) }; static int sceneIdx=-1; @@ -57,6 +42,7 @@ static Layer* nextAction() sceneIdx = sceneIdx % MAX_LAYER; auto layer = (createFunctions[sceneIdx])(); + return layer; } @@ -68,12 +54,14 @@ static Layer* backAction() sceneIdx += total; auto layer = (createFunctions[sceneIdx])(); + return layer; } static Layer* restartAction() { auto layer = (createFunctions[sceneIdx])(); + return layer; } @@ -113,23 +101,26 @@ std::string BaseClippingNodeTest::subtitle() void BaseClippingNodeTest::restartCallback(Object* sender) { - Scene *s = ClippingNodeTestScene::create(); + Scene *s = new ClippingNodeTestScene(); s->addChild(restartAction()); Director::getInstance()->replaceScene(s); + s->release(); } void BaseClippingNodeTest::nextCallback(Object* sender) { - Scene *s = ClippingNodeTestScene::create(); + Scene *s = new ClippingNodeTestScene(); s->addChild(nextAction()); Director::getInstance()->replaceScene(s); + s->release(); } void BaseClippingNodeTest::backCallback(Object* sender) { - Scene *s = ClippingNodeTestScene::create(); + Scene *s = new ClippingNodeTestScene(); s->addChild(backAction()); Director::getInstance()->replaceScene(s); + s->release(); } void BaseClippingNodeTest::setup() diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp index fa9b5b7a4c..7df99cf60e 100644 --- a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp @@ -3,18 +3,12 @@ #include "../testResource.h" #include "cocos2d.h" -TESTLAYER_CREATE_FUNC(ConfigurationLoadConfig); -TESTLAYER_CREATE_FUNC(ConfigurationQuery); -TESTLAYER_CREATE_FUNC(ConfigurationInvalid); -TESTLAYER_CREATE_FUNC(ConfigurationDefault); -TESTLAYER_CREATE_FUNC(ConfigurationSet); - -static NEWTESTFUNC createFunctions[] = { - CF(ConfigurationLoadConfig), - CF(ConfigurationQuery), - CF(ConfigurationInvalid), - CF(ConfigurationDefault), - CF(ConfigurationSet) +static std::function createFunctions[] = { + CL(ConfigurationLoadConfig), + CL(ConfigurationQuery), + CL(ConfigurationInvalid), + CL(ConfigurationDefault), + CL(ConfigurationSet) }; static int sceneIdx=-1; diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp index 66d15719ce..bc2737edf6 100644 --- a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -1,18 +1,11 @@ #include "FileUtilsTest.h" - -TESTLAYER_CREATE_FUNC(TestResolutionDirectories); -TESTLAYER_CREATE_FUNC(TestSearchPath); -TESTLAYER_CREATE_FUNC(TestFilenameLookup); -TESTLAYER_CREATE_FUNC(TestIsFileExist); -TESTLAYER_CREATE_FUNC(TextWritePlist); - -static NEWTESTFUNC createFunctions[] = { - CF(TestResolutionDirectories), - CF(TestSearchPath), - CF(TestFilenameLookup), - CF(TestIsFileExist), - CF(TextWritePlist), +static std::function createFunctions[] = { + CL(TestResolutionDirectories), + CL(TestSearchPath), + CL(TestFilenameLookup), + CL(TestIsFileExist), + CL(TextWritePlist), }; static int sceneIdx=-1; diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 0ede17cec3..1da50ad4ca 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -11,40 +11,23 @@ Layer* nextSchedulerTest(); Layer* backSchedulerTest(); Layer* restartSchedulerTest(); -TESTLAYER_CREATE_FUNC(SchedulerTimeScale) -TESTLAYER_CREATE_FUNC(TwoSchedulers) -TESTLAYER_CREATE_FUNC(SchedulerAutoremove) -TESTLAYER_CREATE_FUNC(SchedulerPauseResume) -TESTLAYER_CREATE_FUNC(SchedulerPauseResumeAll) -TESTLAYER_CREATE_FUNC(SchedulerPauseResumeAllUser) -TESTLAYER_CREATE_FUNC(SchedulerUnscheduleAll) -TESTLAYER_CREATE_FUNC(SchedulerUnscheduleAllHard) -TESTLAYER_CREATE_FUNC(SchedulerUnscheduleAllUserLevel) -TESTLAYER_CREATE_FUNC(SchedulerSchedulesAndRemove) -TESTLAYER_CREATE_FUNC(SchedulerUpdate) -TESTLAYER_CREATE_FUNC(SchedulerUpdateAndCustom) -TESTLAYER_CREATE_FUNC(SchedulerUpdateFromCustom) -TESTLAYER_CREATE_FUNC(RescheduleSelector) -TESTLAYER_CREATE_FUNC(SchedulerDelayAndRepeat) -TESTLAYER_CREATE_FUNC(SchedulerIssue2268) - -static NEWTESTFUNC createFunctions[] = { - CF(SchedulerTimeScale), - CF(TwoSchedulers), - CF(SchedulerAutoremove), - CF(SchedulerPauseResume), - CF(SchedulerPauseResumeAll), - CF(SchedulerPauseResumeAllUser), - CF(SchedulerUnscheduleAll), - CF(SchedulerUnscheduleAllHard), - CF(SchedulerUnscheduleAllUserLevel), - CF(SchedulerSchedulesAndRemove), - CF(SchedulerUpdate), - CF(SchedulerUpdateAndCustom), - CF(SchedulerUpdateFromCustom), - CF(RescheduleSelector), - CF(SchedulerDelayAndRepeat), - CF(SchedulerIssue2268) +static std::function createFunctions[] = { + CL(SchedulerTimeScale), + CL(TwoSchedulers), + CL(SchedulerAutoremove), + CL(SchedulerPauseResume), + CL(SchedulerPauseResumeAll), + CL(SchedulerPauseResumeAllUser), + CL(SchedulerUnscheduleAll), + CL(SchedulerUnscheduleAllHard), + CL(SchedulerUnscheduleAllUserLevel), + CL(SchedulerSchedulesAndRemove), + CL(SchedulerUpdate), + CL(SchedulerUpdateAndCustom), + CL(SchedulerUpdateFromCustom), + CL(RescheduleSelector), + CL(SchedulerDelayAndRepeat), + CL(SchedulerIssue2268) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) diff --git a/samples/Cpp/TestCpp/Classes/testBasic.h b/samples/Cpp/TestCpp/Classes/testBasic.h index 46e07e2c1c..e6ddd8f9f3 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.h +++ b/samples/Cpp/TestCpp/Classes/testBasic.h @@ -17,13 +17,6 @@ public: virtual void runThisTest() = 0; }; -typedef Layer* (*NEWTESTFUNC)(); -#define TESTLAYER_CREATE_FUNC(className) \ -static Layer* create##className() \ -{ return new className(); } - -#define CF(className) create##className - // C++ 11 #define CL(__className__) [](){ return __className__::create();} From 72436c896a69d08b5c8ef6f8adb02a2e8dc0987e Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 13:40:32 -0800 Subject: [PATCH 22/75] prevents bug in gcc 4.6.3 --- samples/Cpp/TestCpp/Classes/testBasic.cpp | 45 ++++++++--------------- 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/samples/Cpp/TestCpp/Classes/testBasic.cpp index 013b5d8563..cffd5acbef 100644 --- a/samples/Cpp/TestCpp/Classes/testBasic.cpp +++ b/samples/Cpp/TestCpp/Classes/testBasic.cpp @@ -19,6 +19,19 @@ TestScene::TestScene(bool bPortrait, bool physics/* = false*/) } } +void testScene_callback( Object *sender ) +{ + auto scene = Scene::create(); + + auto layer = new TestController(); + scene->addChild(layer); + layer->release(); + + Director::getInstance()->replaceScene(scene); + + cocostudio::ArmatureDataManager::destoryInstance(); +} + void TestScene::onEnter() { Scene::onEnter(); @@ -29,36 +42,8 @@ void TestScene::onEnter() //#else auto label = LabelTTF::create("MainMenu", "Arial", 20); //#endif - auto menuItem = MenuItemLabel::create(label, [](Object *sender) { - /* - ****** GCC Compiler issue on Android and Linux (CLANG compiler is ok) ****** - We couldn't use 'Scene::create' directly since gcc will trigger - an error called "error: 'this' was not captured for this lambda function". - This is because 'Scene' is the super class of TestScene, if we invoke 'Scene::create' - directly in this lambda expression, gcc compiler found 'Scene::create' and it think - that was the member function of 'TestScene' 's super class, but this lambda function doesn't - capture anything like 'this', so it has no access to invoke 'Scene::create'. - - Solution (1): Passing 'this' to this lambda function. - Solution (2): Don't use 'Scene::create' and don't pass 'this' to this lambda function, - instead, we just need to new the 'Scene' and initialize the Scene. - - Semantically, I think in this lambda function, we shouldn't capture any varibles - outside the scope. So I choose the (2) solution. Commented by James Chen. - */ - - auto scene = Scene::create(); - - auto layer = new TestController(); - scene->addChild(layer); - layer->release(); - - Director::getInstance()->replaceScene(scene); - - cocostudio::ArmatureDataManager::destoryInstance(); - }); - - auto menu =Menu::create(menuItem, NULL); + auto menuItem = MenuItemLabel::create(label, testScene_callback ); + auto menu = Menu::create(menuItem, NULL); menu->setPosition( Point::ZERO ); menuItem->setPosition( Point( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) ); From 3f1983214f4d03e1e1cbe217cd204a8e2b740815 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 15:07:58 -0800 Subject: [PATCH 23/75] Effects have protected contructors and disallowed copy + assign --- cocos/2d/CCActionGrid.h | 84 ++++--- cocos/2d/CCActionGrid3D.h | 93 +++++-- cocos/2d/CCActionProgressTimer.h | 22 +- cocos/2d/CCActionTiledGrid.h | 124 +++++++--- cocos/2d/CCTransition.h | 410 +++++++++++++------------------ 5 files changed, 398 insertions(+), 335 deletions(-) diff --git a/cocos/2d/CCActionGrid.h b/cocos/2d/CCActionGrid.h index c3daac990d..eb9ddc23a5 100644 --- a/cocos/2d/CCActionGrid.h +++ b/cocos/2d/CCActionGrid.h @@ -41,8 +41,6 @@ class GridBase; class CC_DLL GridAction : public ActionInterval { public: - /** initializes the action with size and duration */ - bool initWithDuration(float duration, const Size& gridSize); /** returns the grid */ virtual GridBase* getGrid(); @@ -53,7 +51,15 @@ public: virtual void startWithTarget(Node *target) override; protected: + GridAction() {} + virtual ~GridAction() {} + /** initializes the action with size and duration */ + bool initWithDuration(float duration, const Size& gridSize); + Size _gridSize; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(GridAction); }; /** @@ -153,18 +159,6 @@ class CC_DLL AccelDeccelAmplitude : public ActionInterval public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static AccelDeccelAmplitude* create(Action *action, float duration); - /** - * @js NA - * @lua NA - */ - virtual ~AccelDeccelAmplitude(); - /** initializes the action with an inner action that has the amplitude property, and a duration time */ - bool initWithAction(Action *pAction, float duration); - - /** returns a new clone of the action */ - virtual AccelDeccelAmplitude* clone() const; - /** returns a new reversed action */ - virtual AccelDeccelAmplitude* reverse() const; /** get amplitude rate */ inline float getRate(void) const { return _rate; } @@ -174,10 +168,20 @@ public: // Overrides virtual void startWithTarget(Node *target) override; virtual void update(float time) override; + virtual AccelDeccelAmplitude* clone() const override; + virtual AccelDeccelAmplitude* reverse() const override; protected: + AccelDeccelAmplitude() {} + virtual ~AccelDeccelAmplitude(); + /** initializes the action with an inner action that has the amplitude property, and a duration time */ + bool initWithAction(Action *pAction, float duration); + float _rate; ActionInterval *_other; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(AccelDeccelAmplitude); }; /** @brief AccelAmplitude action */ @@ -186,14 +190,6 @@ class CC_DLL AccelAmplitude : public ActionInterval public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static AccelAmplitude* create(Action *action, float duration); - /** - * @js NA - * @lua NA - */ - virtual ~AccelAmplitude(); - - /** initializes the action with an inner action that has the amplitude property, and a duration time */ - bool initWithAction(Action *action, float duration); /** get amplitude rate */ inline float getRate() const { return _rate; } @@ -207,8 +203,15 @@ public: virtual AccelAmplitude* reverse() const override; protected: + AccelAmplitude() {} + virtual ~AccelAmplitude(); + bool initWithAction(Action *action, float duration); + float _rate; ActionInterval *_other; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(AccelAmplitude); }; /** @brief DeccelAmplitude action */ @@ -217,13 +220,6 @@ class CC_DLL DeccelAmplitude : public ActionInterval public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static DeccelAmplitude* create(Action *action, float duration); - /** - * @js NA - * @lua NA - */ - virtual ~DeccelAmplitude(); - /** initializes the action with an inner action that has the amplitude property, and a duration time */ - bool initWithAction(Action *action, float duration); /** get amplitude rate */ inline float getRate(void) const { return _rate; } @@ -233,12 +229,20 @@ public: // overrides virtual void startWithTarget(Node *target) override; virtual void update(float time) override; - virtual DeccelAmplitude* clone() const; - virtual DeccelAmplitude* reverse() const; + virtual DeccelAmplitude* clone() const override; + virtual DeccelAmplitude* reverse() const override; protected: + DeccelAmplitude() {} + virtual ~DeccelAmplitude(); + /** initializes the action with an inner action that has the amplitude property, and a duration time */ + bool initWithAction(Action *action, float duration); + float _rate; ActionInterval *_other; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(DeccelAmplitude); }; /** @brief StopGrid action. @@ -256,6 +260,13 @@ public: virtual void startWithTarget(Node *target) override; virtual StopGrid* clone() const override; virtual StopGrid* reverse() const override; + +protected: + StopGrid() {} + virtual ~StopGrid() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(StopGrid); }; /** @brief ReuseGrid action */ @@ -265,16 +276,21 @@ public: /** creates an action with the number of times that the current grid will be reused */ static ReuseGrid* create(int times); - /** initializes an action with the number of times that the current grid will be reused */ - bool initWithTimes(int times); - // Override virtual void startWithTarget(Node *target) override; virtual ReuseGrid* clone() const override; virtual ReuseGrid* reverse() const override; protected: + ReuseGrid() {} + virtual ~ReuseGrid() {} + /** initializes an action with the number of times that the current grid will be reused */ + bool initWithTimes(int times); + int _times; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ReuseGrid); }; // end of actions group diff --git a/cocos/2d/CCActionGrid3D.h b/cocos/2d/CCActionGrid3D.h index 57f868ca55..fbc82f4819 100644 --- a/cocos/2d/CCActionGrid3D.h +++ b/cocos/2d/CCActionGrid3D.h @@ -53,17 +53,22 @@ public: /** sets the ampliture rate */ inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } - /** initializes an action with duration, grid size, waves and amplitude */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); - // Overrides virtual Waves3D* clone() const override; virtual void update(float time) override; protected: + Waves3D() {} + virtual ~Waves3D() {} + /** initializes an action with duration, grid size, waves and amplitude */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); + unsigned int _waves; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Waves3D); }; /** @brief FlipX3D action */ @@ -73,25 +78,36 @@ public: /** creates the action with duration */ static FlipX3D* create(float duration); + // Override + virtual FlipX3D* clone() const override; + virtual void update(float time) override; + +protected: + FlipX3D() {} + virtual ~FlipX3D() {} /** initializes the action with duration */ bool initWithDuration(float duration); virtual bool initWithSize(const Size& gridSize, float duration); - // Override - virtual FlipX3D* clone() const override; - virtual void update(float time) override; +private: + CC_DISALLOW_COPY_AND_ASSIGN(FlipX3D); }; /** @brief FlipY3D action */ class CC_DLL FlipY3D : public FlipX3D { public: + FlipY3D() {} + virtual ~FlipY3D() {} /** creates the action with duration */ static FlipY3D* create(float duration); // Overrides virtual void update(float time) override; virtual FlipY3D* clone() const override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FlipY3D); }; /** @brief Lens3D action */ @@ -111,14 +127,16 @@ public: inline const Point& getPosition() const { return _position; } void setPosition(const Point& position); - /** initializes the action with center position, radius, a grid size and duration */ - bool initWithDuration(float duration, const Size& gridSize, const Point& position, float radius); - // Overrides virtual Lens3D* clone() const override; virtual void update(float time) override; protected: + Lens3D() {} + virtual ~Lens3D() {} + /** initializes the action with center position, radius, a grid size and duration */ + bool initWithDuration(float duration, const Size& gridSize, const Point& position, float radius); + /* lens center position */ Point _position; float _radius; @@ -128,6 +146,9 @@ protected: bool _concave; bool _dirty; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Lens3D); }; /** @brief Ripple3D action */ @@ -148,45 +169,57 @@ public: inline float getAmplitudeRate() const { return _amplitudeRate; } inline void setAmplitudeRate(float fAmplitudeRate) { _amplitudeRate = fAmplitudeRate; } - /** initializes the action with radius, number of waves, amplitude, a grid size and duration */ - bool initWithDuration(float duration, const Size& gridSize, const Point& position, float radius, unsigned int waves, float amplitude); - // Override virtual Ripple3D* clone() const override; virtual void update(float time) override; protected: + Ripple3D() {} + virtual ~Ripple3D() {} + /** initializes the action with radius, number of waves, amplitude, a grid size and duration */ + bool initWithDuration(float duration, const Size& gridSize, const Point& position, float radius, unsigned int waves, float amplitude); + /* center position */ Point _position; float _radius; unsigned int _waves; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Ripple3D); }; /** @brief Shaky3D action */ class CC_DLL Shaky3D : public Grid3DAction { public: + Shaky3D() {} + virtual ~Shaky3D() {} /** creates the action with a range, shake Z vertices, a grid and duration */ static Shaky3D* create(float duration, const Size& gridSize, int range, bool shakeZ); - /** initializes the action with a range, shake Z vertices, a grid and duration */ - bool initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ); - // Overrides virtual Shaky3D* clone() const override; virtual void update(float time) override; protected: + /** initializes the action with a range, shake Z vertices, a grid and duration */ + bool initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ); + int _randrange; bool _shakeZ; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Shaky3D); }; /** @brief Liquid action */ class CC_DLL Liquid : public Grid3DAction { public: + Liquid() {} + virtual ~Liquid() {} /** creates the action with amplitude, a grid and duration */ static Liquid* create(float duration, const Size& gridSize, unsigned int waves, float amplitude); @@ -196,23 +229,28 @@ public: inline float getAmplitudeRate() const { return _amplitudeRate; } inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } - /** initializes the action with amplitude, a grid and duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); - // Overrides virtual Liquid* clone() const override; virtual void update(float time) override; protected: + /** initializes the action with amplitude, a grid and duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); + unsigned int _waves; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Liquid); }; /** @brief Waves action */ class CC_DLL Waves : public Grid3DAction { public: + Waves() {} + virtual ~Waves() {} /** initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration */ static Waves* create(float duration, const Size& gridSize, unsigned int waves, float amplitude, bool horizontal, bool vertical); @@ -222,25 +260,30 @@ public: inline float getAmplitudeRate() const { return _amplitudeRate; } inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } - /** initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude, bool horizontal, bool vertical); - // Overrides virtual Waves* clone() const override; virtual void update(float time) override; protected: + /** initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude, bool horizontal, bool vertical); + unsigned int _waves; float _amplitude; float _amplitudeRate; bool _vertical; bool _horizontal; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Waves); }; /** @brief Twirl action */ class CC_DLL Twirl : public Grid3DAction { public: + Twirl() {} + virtual ~Twirl() {} /** creates the action with center position, number of twirls, amplitude, a grid size and duration */ static Twirl* create(float duration, const Size& gridSize, Point position, unsigned int twirls, float amplitude); @@ -255,19 +298,23 @@ public: inline float getAmplitudeRate() const { return _amplitudeRate; } inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; } - /** initializes the action with center position, number of twirls, amplitude, a grid size and duration */ - bool initWithDuration(float duration, const Size& gridSize, Point position, unsigned int twirls, float amplitude); // Overrides virtual Twirl* clone() const override; virtual void update(float time) override; protected: + /** initializes the action with center position, number of twirls, amplitude, a grid size and duration */ + bool initWithDuration(float duration, const Size& gridSize, Point position, unsigned int twirls, float amplitude); + /* twirl center */ Point _position; unsigned int _twirls; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(Twirl); }; // end of actions group diff --git a/cocos/2d/CCActionProgressTimer.h b/cocos/2d/CCActionProgressTimer.h index de8c2c9c09..dc41237a48 100644 --- a/cocos/2d/CCActionProgressTimer.h +++ b/cocos/2d/CCActionProgressTimer.h @@ -44,9 +44,6 @@ public: /** Creates and initializes with a duration and a percent */ static ProgressTo* create(float duration, float fPercent); - /** Initializes with a duration and a percent */ - bool initWithDuration(float duration, float fPercent); - // // Overrides // @@ -56,8 +53,16 @@ public: virtual void update(float time) override; protected: + ProgressTo() {} + virtual ~ProgressTo() {} + /** Initializes with a duration and a percent */ + bool initWithDuration(float duration, float fPercent); + float _to; float _from; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ProgressTo); }; /** @@ -70,9 +75,6 @@ public: /** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage */ static ProgressFromTo* create(float duration, float fFromPercentage, float fToPercentage); - /** Initializes the action with a duration, a "from" percentage and a "to" percentage */ - bool initWithDuration(float duration, float fFromPercentage, float fToPercentage); - // // Overrides // @@ -82,8 +84,16 @@ public: virtual void update(float time) override; protected: + ProgressFromTo() {} + virtual ~ProgressFromTo() {} + /** Initializes the action with a duration, a "from" percentage and a "to" percentage */ + bool initWithDuration(float duration, float fFromPercentage, float fToPercentage); + float _to; float _from; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ProgressFromTo); }; // end of actions group diff --git a/cocos/2d/CCActionTiledGrid.h b/cocos/2d/CCActionTiledGrid.h index e1471f1ea8..ca4dd786a6 100644 --- a/cocos/2d/CCActionTiledGrid.h +++ b/cocos/2d/CCActionTiledGrid.h @@ -41,16 +41,21 @@ public: /** creates the action with a range, whether or not to shake Z vertices, a grid size, and duration */ static ShakyTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShakeZ); - /** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */ - bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ); - // Override virtual ShakyTiles3D* clone() const override; virtual void update(float time) override; protected: + ShakyTiles3D() {} + virtual ~ShakyTiles3D() {} + /** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */ + bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ); + int _randrange; bool _shakeZ; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ShakyTiles3D); }; /** @brief ShatteredTiles3D action */ @@ -60,17 +65,22 @@ public: /** creates the action with a range, whether of not to shatter Z vertices, a grid size and duration */ static ShatteredTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShatterZ); - /** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */ - bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ); - // Override virtual ShatteredTiles3D* clone() const override; virtual void update(float time) override; protected: + ShatteredTiles3D() {} + virtual ~ShatteredTiles3D() {} + /** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */ + bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ); + int _randrange; bool _once; bool _shatterZ; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ShatteredTiles3D); }; struct Tile; @@ -82,13 +92,6 @@ class CC_DLL ShuffleTiles : public TiledGrid3DAction public: /** creates the action with a random seed, the grid size and the duration */ static ShuffleTiles* create(float duration, const Size& gridSize, unsigned int seed); - /** - * @js NA - * @lua NA - */ - virtual ~ShuffleTiles(void); - /** initializes the action with a random seed, the grid size and the duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int seed); void shuffle(unsigned int *array, unsigned int nLen); Size getDelta(const Size& pos) const; @@ -100,10 +103,18 @@ public: virtual ShuffleTiles* clone() const override; protected: + ShuffleTiles() {} + virtual ~ShuffleTiles(); + /** initializes the action with a random seed, the grid size and the duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int seed); + unsigned int _seed; unsigned int _tilesCount; unsigned int* _tilesOrder; Tile* _tiles; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(ShuffleTiles); }; /** @brief FadeOutTRTiles action @@ -123,6 +134,13 @@ public: // Overrides virtual void update(float time) override; virtual FadeOutTRTiles* clone() const override; + +protected: + FadeOutTRTiles() {} + virtual ~FadeOutTRTiles() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeOutTRTiles); }; /** @brief FadeOutBLTiles action. @@ -137,6 +155,13 @@ public: // Overrides virtual float testFunc(const Size& pos, float time) override; virtual FadeOutBLTiles* clone() const override; + +protected: + FadeOutBLTiles() {} + virtual ~FadeOutBLTiles() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeOutBLTiles); }; /** @brief FadeOutUpTiles action. @@ -153,6 +178,13 @@ public: // Overrides virtual FadeOutUpTiles* clone() const override; virtual float testFunc(const Size& pos, float time) override; + +protected: + FadeOutUpTiles() {} + virtual ~FadeOutUpTiles() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeOutUpTiles); }; /** @brief FadeOutDownTiles action. @@ -167,6 +199,13 @@ public: // Overrides virtual FadeOutDownTiles* clone() const override; virtual float testFunc(const Size& pos, float time) override; + +protected: + FadeOutDownTiles() {} + virtual ~FadeOutDownTiles() {} + +private: + CC_DISALLOW_COPY_AND_ASSIGN(FadeOutDownTiles); }; /** @brief TurnOffTiles action. @@ -179,13 +218,6 @@ public: static TurnOffTiles* create(float duration, const Size& gridSize); /** creates the action with a random seed, the grid size and the duration */ static TurnOffTiles* create(float duration, const Size& gridSize, unsigned int seed); - /** - * @js NA - * @lua NA - */ - ~TurnOffTiles(void); - /** initializes the action with a random seed, the grid size and the duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int seed); void shuffle(unsigned int *pArray, unsigned int nLen); void turnOnTile(const Point& pos); @@ -197,9 +229,17 @@ public: virtual void update(float time) override; protected: + TurnOffTiles() {} + virtual ~TurnOffTiles(); + /** initializes the action with a random seed, the grid size and the duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int seed); + unsigned int _seed; unsigned int _tilesCount; unsigned int* _tilesOrder; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TurnOffTiles); }; /** @brief WavesTiles3D action. */ @@ -209,9 +249,6 @@ public: /** creates the action with a number of waves, the waves amplitude, the grid size and the duration */ static WavesTiles3D* create(float duration, const Size& gridSize, unsigned int waves, float amplitude); - /** initializes the action with a number of waves, the waves amplitude, the grid size and the duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); - /** waves amplitude */ inline float getAmplitude(void) const { return _amplitude; } inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } @@ -225,9 +262,17 @@ public: virtual void update(float time) override; protected: + WavesTiles3D() {} + virtual ~WavesTiles3D() {} + /** initializes the action with a number of waves, the waves amplitude, the grid size and the duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude); + unsigned int _waves; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(WavesTiles3D); }; /** @brief JumpTiles3D action. @@ -239,9 +284,6 @@ public: /** creates the action with the number of jumps, the sin amplitude, the grid size and the duration */ static JumpTiles3D* create(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude); - /** initializes the action with the number of jumps, the sin amplitude, the grid size and the duration */ - bool initWithDuration(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude); - /** amplitude of the sin*/ inline float getAmplitude(void) const { return _amplitude; } inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } @@ -255,9 +297,17 @@ public: virtual void update(float time) override; protected: + JumpTiles3D() {} + virtual ~JumpTiles3D() {} + /** initializes the action with the number of jumps, the sin amplitude, the grid size and the duration */ + bool initWithDuration(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude); + unsigned int _jumps; float _amplitude; float _amplitudeRate; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(JumpTiles3D); }; /** @brief SplitRows action */ @@ -267,17 +317,22 @@ public : /** creates the action with the number of rows to split and the duration */ static SplitRows* create(float duration, unsigned int nRows); - /** initializes the action with the number of rows to split and the duration */ - bool initWithDuration(float duration, unsigned int nRows); - // Overrides virtual SplitRows* clone() const override; virtual void update(float time) override; virtual void startWithTarget(Node *target) override; protected: + SplitRows() {} + virtual ~SplitRows() {} + /** initializes the action with the number of rows to split and the duration */ + bool initWithDuration(float duration, unsigned int nRows); + unsigned int _rows; Size _winSize; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(SplitRows); }; /** @brief SplitCols action */ @@ -287,17 +342,22 @@ public: /** creates the action with the number of columns to split and the duration */ static SplitCols* create(float duration, unsigned int nCols); - /** initializes the action with the number of columns to split and the duration */ - bool initWithDuration(float duration, unsigned int nCols); - // Overrides virtual SplitCols* clone() const override; virtual void update(float time) override; virtual void startWithTarget(Node *target) override; protected: + SplitCols() {} + virtual ~SplitCols() {} + /** initializes the action with the number of columns to split and the duration */ + bool initWithDuration(float duration, unsigned int nCols); + unsigned int _cols; Size _winSize; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(SplitCols); }; // end of actions group diff --git a/cocos/2d/CCTransition.h b/cocos/2d/CCTransition.h index 43f1fe5bee..f2485d016e 100644 --- a/cocos/2d/CCTransition.h +++ b/cocos/2d/CCTransition.h @@ -90,33 +90,24 @@ public: // Overrides // virtual void draw() override; - /** - * @js NA - * @lua NA - */ virtual void onEnter() override; - /** - * @js NA - * @lua NA - */ virtual void onExit() override; virtual void cleanup() override; protected: TransitionScene(); virtual ~TransitionScene(); - /** initializes a transition with duration and incoming scene */ bool initWithDuration(float t,Scene* scene); virtual void sceneOrder(); void setNewScene(float dt); - Scene * _inScene; - Scene * _outScene; - float _duration; - bool _isInSceneOnTop; - bool _isSendCleanupToScene; + Scene *_inScene; + Scene *_outScene; + float _duration; + bool _isInSceneOnTop; + bool _isSendCleanupToScene; private: CC_DISALLOW_COPY_AND_ASSIGN(TransitionScene); @@ -152,14 +143,9 @@ class CC_DLL TransitionRotoZoom : public TransitionScene public: static TransitionRotoZoom* create(float t, Scene* scene); - // // Overrides // - /** - * @js NA - * @lua NA - */ virtual void onEnter() override; protected: @@ -182,10 +168,6 @@ public: // // Overrides // - /** - * @js NA - * @lua NA - */ virtual void onEnter() override; protected: @@ -204,8 +186,6 @@ class CC_DLL TransitionMoveInL : public TransitionScene, public TransitionEaseSc public: static TransitionMoveInL* create(float t, Scene* scene); - /** initializes the scenes */ - virtual void initScenes(void); /** returns the action that will be performed */ virtual ActionInterval* action(void); @@ -214,16 +194,15 @@ public: // // Overrides // - /** - * @js NA - * @lua NA - */ virtual void onEnter() override; protected: TransitionMoveInL(); virtual ~TransitionMoveInL(); + /** initializes the scenes */ + virtual void initScenes(); + private: CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInL); }; @@ -235,12 +214,13 @@ class CC_DLL TransitionMoveInR : public TransitionMoveInL { public: static TransitionMoveInR* create(float t, Scene* scene); - virtual void initScenes(); protected: TransitionMoveInR(); virtual ~TransitionMoveInR(); + virtual void initScenes(); + private: CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInR); }; @@ -252,12 +232,13 @@ class CC_DLL TransitionMoveInT : public TransitionMoveInL { public: static TransitionMoveInT* create(float t, Scene* scene); - virtual void initScenes(); protected: TransitionMoveInT(); virtual ~TransitionMoveInT(); + virtual void initScenes(); + private: CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInT); }; @@ -269,19 +250,13 @@ class CC_DLL TransitionMoveInB : public TransitionMoveInL { public: static TransitionMoveInB* create(float t, Scene* scene); - virtual void initScenes(); protected: - /** - * @js ctor - */ TransitionMoveInB(); - /** - * @js NA - * @lua NA - */ virtual ~TransitionMoveInB(); + virtual void initScenes(); + private: CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInB); }; @@ -296,31 +271,21 @@ public: virtual ActionInterval* easeActionWithAction(ActionInterval * action); - /** initializes the scenes */ - virtual void initScenes(void); /** returns the action that will be performed by the incoming and outgoing scene */ virtual ActionInterval* action(void); // // Overrides // - /** - * @js NA - * @lua NA - */ virtual void onEnter() override; protected: - /** - * @js ctor - */ TransitionSlideInL(); - /** - * @js NA - * @lua NA - */ virtual ~TransitionSlideInL(); + /** initializes the scenes */ + virtual void initScenes(void); + virtual void sceneOrder() override; private: @@ -334,23 +299,21 @@ class CC_DLL TransitionSlideInR : public TransitionSlideInL { public: static TransitionSlideInR* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSlideInR(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSlideInR(); - /** initializes the scenes */ - virtual void initScenes(void); /** returns the action that will be performed by the incoming and outgoing scene */ virtual ActionInterval* action(void); protected: + TransitionSlideInR(); + virtual ~TransitionSlideInR(); + + /** initializes the scenes */ + virtual void initScenes(void); + virtual void sceneOrder() override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInR); }; /** @brief TransitionSlideInB: @@ -360,23 +323,21 @@ class CC_DLL TransitionSlideInB : public TransitionSlideInL { public: static TransitionSlideInB* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSlideInB(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSlideInB(); - /** initializes the scenes */ - virtual void initScenes(void); /** returns the action that will be performed by the incoming and outgoing scene */ virtual ActionInterval* action(void); protected: + TransitionSlideInB(); + virtual ~TransitionSlideInB(); + + /** initializes the scenes */ + virtual void initScenes(); + virtual void sceneOrder() override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInB); }; /** @brief TransitionSlideInT: @@ -386,23 +347,21 @@ class CC_DLL TransitionSlideInT : public TransitionSlideInL { public: static TransitionSlideInT* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSlideInT(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSlideInT(); - /** initializes the scenes */ - virtual void initScenes(void); /** returns the action that will be performed by the incoming and outgoing scene */ virtual ActionInterval* action(void); protected: + TransitionSlideInT(); + virtual ~TransitionSlideInT(); + + /** initializes the scenes */ + virtual void initScenes(void); + virtual void sceneOrder() override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInT); }; /** @@ -412,21 +371,23 @@ class CC_DLL TransitionShrinkGrow : public TransitionScene , public TransitionEa { public: static TransitionShrinkGrow* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionShrinkGrow(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionShrinkGrow(); // // Overrides // + /** + * @js NA + * @lua NA + */ virtual void onEnter() override; virtual ActionInterval* easeActionWithAction(ActionInterval * action) override; + +protected: + TransitionShrinkGrow(); + virtual ~TransitionShrinkGrow(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionShrinkGrow); }; /** @brief TransitionFlipX: @@ -438,15 +399,6 @@ class CC_DLL TransitionFlipX : public TransitionSceneOriented public: static TransitionFlipX* create(float t, Scene* s, Orientation o); static TransitionFlipX* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionFlipX(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFlipX(); // // Overrides @@ -456,6 +408,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionFlipX(); + virtual ~TransitionFlipX(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipX); }; /** @brief TransitionFlipY: @@ -467,15 +426,6 @@ class CC_DLL TransitionFlipY : public TransitionSceneOriented public: static TransitionFlipY* create(float t, Scene* s, Orientation o); static TransitionFlipY* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionFlipY(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFlipY(); // // Overrides @@ -485,6 +435,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionFlipY(); + virtual ~TransitionFlipY(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipY); }; /** @brief TransitionFlipAngular: @@ -496,15 +453,6 @@ class CC_DLL TransitionFlipAngular : public TransitionSceneOriented public: static TransitionFlipAngular* create(float t, Scene* s, Orientation o); static TransitionFlipAngular* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionFlipAngular(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFlipAngular(); // // Overrides @@ -514,6 +462,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionFlipAngular(); + virtual ~TransitionFlipAngular(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipAngular); }; /** @brief TransitionZoomFlipX: @@ -525,15 +480,6 @@ class CC_DLL TransitionZoomFlipX : public TransitionSceneOriented public: static TransitionZoomFlipX* create(float t, Scene* s, Orientation o); static TransitionZoomFlipX* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionZoomFlipX(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionZoomFlipX(); // // Overrides @@ -543,6 +489,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionZoomFlipX(); + virtual ~TransitionZoomFlipX(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipX); }; /** @brief TransitionZoomFlipY: @@ -554,15 +507,6 @@ class CC_DLL TransitionZoomFlipY : public TransitionSceneOriented public: static TransitionZoomFlipY* create(float t, Scene* s, Orientation o); static TransitionZoomFlipY* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionZoomFlipY(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionZoomFlipY(); // // Overrides @@ -572,6 +516,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionZoomFlipY(); + virtual ~TransitionZoomFlipY(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipY); }; /** @brief TransitionZoomFlipAngular: @@ -583,15 +534,6 @@ class CC_DLL TransitionZoomFlipAngular : public TransitionSceneOriented public: static TransitionZoomFlipAngular* create(float t, Scene* s, Orientation o); static TransitionZoomFlipAngular* create(float t, Scene* s); - /** - * @js ctor - */ - TransitionZoomFlipAngular(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionZoomFlipAngular(); // // Overrides @@ -601,6 +543,13 @@ public: * @lua NA */ virtual void onEnter() override; + +protected: + TransitionZoomFlipAngular(); + virtual ~TransitionZoomFlipAngular(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipAngular); }; /** @brief TransitionFade: @@ -612,25 +561,9 @@ public: /** creates the transition with a duration and with an RGB color * Example: FadeTransition::create(2, scene, Color3B(255,0,0); // red color */ - static TransitionFade* create(float duration,Scene* scene, const Color3B& color); - static TransitionFade* create(float duration,Scene* scene); - /** - * @js ctor - */ - TransitionFade(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFade(); + static TransitionFade* create(float duration, Scene* scene, const Color3B& color); + static TransitionFade* create(float duration, Scene* scene); - /** initializes the transition with a duration and with an RGB color */ - bool initWithDuration(float t, Scene*scene ,const Color3B& color); - - // - // Overrides - // - bool initWithDuration(float t,Scene* scene); /** * @js NA * @lua NA @@ -643,7 +576,18 @@ public: virtual void onExit(); protected: - Color4B _color; + TransitionFade(); + virtual ~TransitionFade(); + + /** initializes the transition with a duration and with an RGB color */ + bool initWithDuration(float t, Scene*scene, const Color3B& color); + bool initWithDuration(float t, Scene* scene); + + Color4B _color; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFade); + }; class RenderTexture; @@ -655,19 +599,14 @@ class CC_DLL TransitionCrossFade : public TransitionScene { public : static TransitionCrossFade* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionCrossFade(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionCrossFade(); // // Overrides // + /** + * @js NA + * @lua NA + */ virtual void draw() override; /** * @js NA @@ -680,6 +619,12 @@ public : */ virtual void onExit() override; +protected: + TransitionCrossFade(); + virtual ~TransitionCrossFade(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionCrossFade); }; /** @brief TransitionTurnOffTiles: @@ -689,15 +634,6 @@ class CC_DLL TransitionTurnOffTiles : public TransitionScene ,public TransitionE { public : static TransitionTurnOffTiles* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionTurnOffTiles(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionTurnOffTiles(); // // Overrides @@ -710,7 +646,13 @@ public : virtual ActionInterval * easeActionWithAction(ActionInterval * action) override; protected: + TransitionTurnOffTiles(); + virtual ~TransitionTurnOffTiles(); + virtual void sceneOrder() override; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionTurnOffTiles); }; /** @brief TransitionSplitCols: @@ -720,17 +662,8 @@ class CC_DLL TransitionSplitCols : public TransitionScene , public TransitionEas { public: static TransitionSplitCols* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSplitCols(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSplitCols(); - virtual ActionInterval* action(void); + virtual ActionInterval* action(); // // Overrides @@ -741,6 +674,13 @@ public: */ virtual void onEnter() override; virtual ActionInterval * easeActionWithAction(ActionInterval * action) override; + +protected: + TransitionSplitCols(); + virtual ~TransitionSplitCols(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitCols); }; /** @brief TransitionSplitRows: @@ -750,20 +690,18 @@ class CC_DLL TransitionSplitRows : public TransitionSplitCols { public: static TransitionSplitRows* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionSplitRows(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionSplitRows(); // // Overrides // virtual ActionInterval* action(void) override; + +protected: + TransitionSplitRows(); + virtual ~TransitionSplitRows(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitRows); }; /** @brief TransitionFadeTR: @@ -773,15 +711,7 @@ class CC_DLL TransitionFadeTR : public TransitionScene , public TransitionEaseSc { public: static TransitionFadeTR* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionFadeTR(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFadeTR(); + virtual ActionInterval* actionWithSize(const Size& size); // @@ -795,7 +725,13 @@ public: virtual ActionInterval* easeActionWithAction(ActionInterval * action) override; protected: + TransitionFadeTR(); + virtual ~TransitionFadeTR(); + virtual void sceneOrder(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeTR); }; /** @brief TransitionFadeBL: @@ -805,21 +741,18 @@ class CC_DLL TransitionFadeBL : public TransitionFadeTR { public: static TransitionFadeBL* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionFadeBL(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFadeBL(); // // Overrides // virtual ActionInterval* actionWithSize(const Size& size) override; +protected: + TransitionFadeBL(); + virtual ~TransitionFadeBL(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeBL); }; /** @brief TransitionFadeUp: @@ -829,20 +762,18 @@ class CC_DLL TransitionFadeUp : public TransitionFadeTR { public: static TransitionFadeUp* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionFadeUp(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFadeUp(); // // Overrides // virtual ActionInterval* actionWithSize(const Size& size) override; + +protected: + TransitionFadeUp(); + virtual ~TransitionFadeUp(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeUp); }; /** @brief TransitionFadeDown: @@ -852,20 +783,19 @@ class CC_DLL TransitionFadeDown : public TransitionFadeTR { public: static TransitionFadeDown* create(float t, Scene* scene); - /** - * @js ctor - */ - TransitionFadeDown(); - /** - * @js NA - * @lua NA - */ - virtual ~TransitionFadeDown(); // // Overrides // virtual ActionInterval* actionWithSize(const Size& size) override; + +protected: + TransitionFadeDown(); + virtual ~TransitionFadeDown(); + +private: + CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeDown); + }; // end of transition group From 9b52af010d087d651b3fd4e10f34f3b4fd80323a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 16:09:05 -0800 Subject: [PATCH 24/75] Macro CC_DISABLE_COPY is renamed to CC_DISALLOW_COPY_AND_ASSIGN and the old CC_DISALLOW_COPY_AND_ASSIGN is removed --- cocos/2d/ccMacros.h | 18 ---------------- cocos/2d/platform/CCDevice.h | 6 ++++-- cocos/2d/platform/CCEGLViewProtocol.cpp | 11 ++++------ cocos/2d/platform/CCEGLViewProtocol.h | 14 ++++++------- cocos/2d/platform/mac/CCEGLView.mm | 4 ++-- cocos/base/CCPlatformMacros.h | 28 +++++++++++++++++-------- 6 files changed, 36 insertions(+), 45 deletions(-) diff --git a/cocos/2d/ccMacros.h b/cocos/2d/ccMacros.h index f82f3c9284..dbea2d512a 100644 --- a/cocos/2d/ccMacros.h +++ b/cocos/2d/ccMacros.h @@ -257,22 +257,4 @@ extern unsigned int CC_DLL g_uNumberOfDraws; */ #define AnimationFrameDisplayedNotification "CCAnimationFrameDisplayedNotification" -// A macro to disallow the copy constructor and operator= functions -// This should be used in the private: declarations for a class -#define CC_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) - -// A macro to disallow all the implicit constructors, namely the -// default constructor, copy constructor and operator= functions. -// -// This should be used in the private: declarations for a class -// that wants to prevent anyone from instantiating it. This is -// especially useful for classes containing only static methods. -#define CC_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ - TypeName(); \ - CC_DISALLOW_COPY_AND_ASSIGN(TypeName) - - - #endif // __CCMACROS_H__ diff --git a/cocos/2d/platform/CCDevice.h b/cocos/2d/platform/CCDevice.h index 1a7ddc0e72..65d5a3f3b7 100644 --- a/cocos/2d/platform/CCDevice.h +++ b/cocos/2d/platform/CCDevice.h @@ -2,13 +2,12 @@ #define __CCDEVICE_H__ #include "CCPlatformMacros.h" +#include "ccMacros.h" NS_CC_BEGIN class CC_DLL Device { -private: - Device(); public: /** * Gets the DPI of device @@ -24,6 +23,9 @@ public: * Sets the interval of accelerometer. */ static void setAccelerometerInterval(float interval); + +private: + CC_DISALLOW_IMPLICIT_CONSTRUCTORS(Device); }; diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCEGLViewProtocol.cpp index ebeba6b203..c6623a234f 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCEGLViewProtocol.cpp @@ -177,7 +177,7 @@ bool EGLViewProtocol::isScissorEnabled() return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true; } -Rect EGLViewProtocol::getScissorRect() +Rect EGLViewProtocol::getScissorRect() const { GLfloat params[4]; glGetFloatv(GL_SCISSOR_BOX, params); @@ -188,15 +188,12 @@ Rect EGLViewProtocol::getScissorRect() return Rect(x, y, w, h); } -void EGLViewProtocol::setViewName(const char* pszViewName) +void EGLViewProtocol::setViewName(const std::string& viewname ) { - if (pszViewName != NULL && strlen(pszViewName) > 0) - { - strncpy(_viewName, pszViewName, sizeof(_viewName)); - } + _viewName = viewname; } -const char* EGLViewProtocol::getViewName() +const std::string& EGLViewProtocol::getViewName() const { return _viewName; } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCEGLViewProtocol.h index ed54d59712..53f9400dcf 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCEGLViewProtocol.h @@ -129,11 +129,10 @@ public: /** * Get the current scissor rectangle */ - virtual Rect getScissorRect(); + virtual Rect getScissorRect() const; - virtual void setViewName(const char* pszViewName); - - const char* getViewName(); + virtual void setViewName(const std::string& viewname); + const std::string& getViewName() const; /** Touch events are handled by default; if you want to customize your handlers, please override these functions: */ virtual void handleTouchesBegin(int num, long ids[], float xs[], float ys[]); @@ -155,10 +154,11 @@ public: * Get scale factor of the vertical direction. */ float getScaleY() const; -private: - void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); + protected: + void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, long ids[], float xs[], float ys[]); + EGLTouchDelegate* _delegate; // real screen size @@ -168,7 +168,7 @@ protected: // the view port size Rect _viewPortRect; // the view name - char _viewName[50]; + std::string _viewName; float _scaleX; float _scaleY; diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index 04ef6b69e7..5d4f23b281 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -312,8 +312,8 @@ EGLView::EGLView() , _mainWindow(nullptr) { CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); + _viewName = "cocos2dx"; s_pEglView = this; - strcpy(_viewName, "Cocos2dxWin32"); glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); glfwInit(); } @@ -334,7 +334,7 @@ bool EGLView::init(const char *viewName, float width, float height, float frameZ setFrameZoomFactor(frameZoomFactor); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName, nullptr, nullptr); + _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); glfwMakeContextCurrent(_mainWindow); glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); diff --git a/cocos/base/CCPlatformMacros.h b/cocos/base/CCPlatformMacros.h index fca1255c0d..f3c8c91ba7 100644 --- a/cocos/base/CCPlatformMacros.h +++ b/cocos/base/CCPlatformMacros.h @@ -234,19 +234,29 @@ public: virtual void set##funName(varType var) \ #define LUALOG(format, ...) cocos2d::log(format, ##__VA_ARGS__) #endif // Lua engine debug +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class #if defined(__GNUC__) && ((__GNUC__ >= 5) || ((__GNUG__ == 4) && (__GNUC_MINOR__ >= 4))) \ - || (defined(__clang__) && (__clang_major__ >= 3)) -#define CC_DISABLE_COPY(Class) \ -private: \ - Class(const Class &) = delete; \ - Class &operator =(const Class &) = delete; +|| (defined(__clang__) && (__clang_major__ >= 3)) +#define CC_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &) = delete; \ + TypeName &operator =(const TypeName &) = delete; #else -#define CC_DISABLE_COPY(Class) \ -private: \ - Class(const Class &); \ - Class &operator =(const Class &); +#define CC_DISALLOW_COPY_AND_ASSIGN(TypeName) \ + Class(const TypeName &); \ + Class &operator =(const TypeName &); #endif +// A macro to disallow all the implicit constructors, namely the +// default constructor, copy constructor and operator= functions. +// +// This should be used in the private: declarations for a class +// that wants to prevent anyone from instantiating it. This is +// especially useful for classes containing only static methods. +#define CC_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName(); \ + CC_DISALLOW_COPY_AND_ASSIGN(TypeName) + /* * only certain compilers support __attribute__((deprecated)) */ From 447a34655ac71069adb5542fb56425852e736fce Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 16:14:05 -0800 Subject: [PATCH 25/75] RenderTexture contructor ctor is public again --- cocos/2d/CCRenderTexture.h | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index 90b2ba1784..5837848eab 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -152,23 +152,18 @@ public: virtual void visit() override; virtual void draw() override; -protected: - /** - * @js ctor - */ +public: + // XXX should be procted. + // but due to a bug in PowerVR + Android, + // the constructor is public again RenderTexture(); - /** - * @js NA - * @lua NA - */ virtual ~RenderTexture(); - /** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat); - /** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/ bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat); +protected: void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue, GLbitfield flags); GLuint _FBO; From cc5a03f21a0e9c324bb9848de34f5fd7552008bd Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 22 Nov 2013 16:58:05 -0800 Subject: [PATCH 26/75] updates cocos2d version --- cocos/2d/cocos2d.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/cocos2d.cpp b/cocos/2d/cocos2d.cpp index d531f85893..1c754fd45b 100644 --- a/cocos/2d/cocos2d.cpp +++ b/cocos/2d/cocos2d.cpp @@ -30,7 +30,7 @@ NS_CC_BEGIN const char* cocos2dVersion() { - return "3.0-alpha1"; + return "3.0-beta0-pre"; } NS_CC_END From f2dabe77ec431713107fa7010c07c7ea9aea23cc Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 25 Nov 2013 10:08:52 +0800 Subject: [PATCH 27/75] issue #2771: add some method implements with box2d in PhysicsWorld --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/physics/CCPhysicsContact.cpp | 3 + cocos/physics/CCPhysicsSetting.h | 5 +- cocos/physics/CCPhysicsWorld.cpp | 385 +++++++++--------- cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h | 11 +- .../box2d/CCPhysicsContactInfo_box2d.cpp | 3 +- .../box2d/CCPhysicsContactInfo_box2d.h | 3 +- cocos/physics/box2d/CCPhysicsHelper_box2d.h | 4 + .../box2d/CCPhysicsJointInfo_box2d.cpp | 4 +- .../physics/box2d/CCPhysicsJointInfo_box2d.h | 4 +- .../box2d/CCPhysicsShapeInfo_box2d.cpp | 3 +- .../physics/box2d/CCPhysicsShapeInfo_box2d.h | 7 +- .../box2d/CCPhysicsWorldInfo_box2d.cpp | 28 ++ .../physics/box2d/CCPhysicsWorldInfo_box2d.h | 15 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 16 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 12 +- 16 files changed, 297 insertions(+), 208 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 692b7ad548..3143ef614d 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1dbcea49018d245ac72bf4138633f3905ef4dc7f \ No newline at end of file +820d4d91d031eb7dde2f974508e61dac29d1a8d1 \ No newline at end of file diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index af2a51e238..5fe324f3ed 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -95,6 +95,7 @@ bool PhysicsContact::init(PhysicsShape* a, PhysicsShape* b) return false; } +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) void PhysicsContact::generateContactData() { if (_contactInfo == nullptr) @@ -496,6 +497,8 @@ EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::clon CC_SAFE_DELETE(obj); return nullptr; } +#else +#endif NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index 9eb82f2fa2..64071e4425 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -29,7 +29,7 @@ #define CC_PHYSICS_BOX2D 1 #define CC_PHYSICS_CHIPMUNK 2 -#define CC_USE_CHIPMUNK +#define CC_USE_BOX2D #ifdef CC_USE_BOX2D #define CC_PHYSICS_ENGINE CC_PHYSICS_BOX2D @@ -51,8 +51,9 @@ namespace cocos2d typedef Point Vect; #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - static const int PHYSICS_CONTACT_POINT_MAX = 4; + static const long PHYSICS_CONTACT_POINT_MAX = 4; #else + static const long PHYSICS_CONTACT_POINT_MAX = 2; #endif } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 1e1e06c4c6..59d7db9ae9 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -201,81 +201,6 @@ void PhysicsWorldCallback::queryPointFunc(cpShape *shape, cpFloat distance, cpVe PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } -bool PhysicsWorld::init(Scene& scene) -{ - do - { - _delayAddBodies = Array::create(); - _delayRemoveBodies = Array::create(); - CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); - _delayAddBodies->retain(); - _delayRemoveBodies->retain(); - - _info = new PhysicsWorldInfo(); - CC_BREAK_IF(_info == nullptr); - _bodies = Array::create(); - CC_BREAK_IF(_bodies == nullptr); - _bodies->retain(); - - _scene = &scene; - - cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(_gravity)); - - cpSpaceSetDefaultCollisionHandler(_info->getSpace(), - (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, - (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, - (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, - (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, - this); - - return true; - } while (false); - - return false; -} - -void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) -{ - if (_delayRemoveBodies->getIndexOfObject(body) != CC_INVALID_INDEX) - { - _delayRemoveBodies->removeObject(body); - return; - } - - if (_info->getSpace()->locked_private) - { - if (_delayAddBodies->getIndexOfObject(body) == CC_INVALID_INDEX) - { - _delayAddBodies->addObject(body); - _delayDirty = true; - } - }else - { - doAddBody(body); - } -} - -void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) -{ - if (_delayAddBodies->getIndexOfObject(body) != CC_INVALID_INDEX) - { - _delayAddBodies->removeObject(body); - return; - } - - if (_info->getSpace()->locked_private) - { - if (_delayRemoveBodies->getIndexOfObject(body) == CC_INVALID_INDEX) - { - _delayRemoveBodies->addObject(body); - _delayDirty = true; - } - }else - { - doRemoveBody(body); - } -} - void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) { auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); @@ -426,98 +351,6 @@ void PhysicsWorld::doAddJoint(PhysicsJoint *joint) } } -void PhysicsWorld::doAddBody(PhysicsBody* body) -{ - if (body->isEnabled()) - { - //is gravity enable - if (!body->isGravityEnabled()) - { - body->applyForce(-_gravity); - } - - // add body to space - if (body->isDynamic()) - { - _info->addBody(body->_info->getBody()); - } - - // add shapes to space - for (auto shape : *body->getShapes()) - { - addShape(dynamic_cast(shape)); - } - } -} - -void PhysicsWorld::addBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - if (body->getWorld() == this) - { - return; - } - - if (body->getWorld() != nullptr) - { - body->removeFromWorld(); - } - - addBodyOrDelay(body); - _bodies->addObject(body); - body->_world = this; -} - -void PhysicsWorld::removeBody(PhysicsBody* body) -{ - - if (body->getWorld() != this) - { - CCLOG("Physics Warnning: this body doesn't belong to this world"); - return; - } - - // destory the body's joints - for (auto joint : body->_joints) - { - // set destroy param to false to keep the iterator available - removeJoint(joint, false); - - PhysicsBody* other = (joint->getBodyA() == body ? joint->getBodyB() : body); - other->removeJoint(joint); - - // test the distraction is delaied or not - if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) - { - joint->_destoryMark = true; - } - else - { - delete joint; - } - } - - body->_joints.clear(); - - removeBodyOrDelay(body); - _bodies->removeObject(body); - body->_world = nullptr; -} - -void PhysicsWorld::removeBody(int tag) -{ - for (Object* obj : *_bodies) - { - PhysicsBody* body = dynamic_cast(obj); - if (body->getTag() == tag) - { - removeBody(body); - return; - } - } -} - void PhysicsWorld::doRemoveBody(PhysicsBody* body) { CCASSERT(body != nullptr, "the body can not be nullptr"); @@ -535,7 +368,7 @@ void PhysicsWorld::doRemoveBody(PhysicsBody* body) } // remove body - _info->removeBody(body->_info->getBody()); + _info->removeBody(*body->_info); } void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) @@ -570,27 +403,6 @@ void PhysicsWorld::removeShape(PhysicsShape* shape) } } -void PhysicsWorld::updateBodies() -{ - if (_info->getSpace()->locked_private) - { - return; - } - - for (auto body : *_delayAddBodies) - { - doAddBody(dynamic_cast(body)); - } - - for (auto body : *_delayRemoveBodies) - { - doRemoveBody(dynamic_cast(body)); - } - - _delayAddBodies->removeAllObjects(); - _delayRemoveBodies->removeAllObjects(); -} - void PhysicsWorld::updateJoints() { if (_info->getSpace()->locked_private) @@ -1047,6 +859,199 @@ PhysicsWorld* PhysicsWorld::construct(Scene& scene) return nullptr; } +bool PhysicsWorld::init(Scene& scene) +{ + do + { + _delayAddBodies = Array::create(); + _delayRemoveBodies = Array::create(); + CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); + _delayAddBodies->retain(); + _delayRemoveBodies->retain(); + + _info = new PhysicsWorldInfo(); + CC_BREAK_IF(_info == nullptr); + _bodies = Array::create(); + CC_BREAK_IF(_bodies == nullptr); + _bodies->retain(); + + _scene = &scene; + + _info->setGravity(_gravity); + +#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) + cpSpaceSetDefaultCollisionHandler(_info->getSpace(), + (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, + (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, + (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, + (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, + this); +#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#endif + + return true; + } while (false); + + return false; +} + +void PhysicsWorld::addBody(PhysicsBody* body) +{ + CCASSERT(body != nullptr, "the body can not be nullptr"); + + if (body->getWorld() == this) + { + return; + } + + if (body->getWorld() != nullptr) + { + body->removeFromWorld(); + } + + addBodyOrDelay(body); + _bodies->addObject(body); + body->_world = this; +} + +void PhysicsWorld::doAddBody(PhysicsBody* body) +{ + if (body->isEnabled()) + { + //is gravity enable + if (!body->isGravityEnabled()) + { + body->applyForce(-_gravity); + } + + // add body to space + if (body->isDynamic()) + { + _info->addBody(*body->_info); + } + + // add shapes to space + for (auto shape : *body->getShapes()) + { + addShape(dynamic_cast(shape)); + } + } +} + + +void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) +{ + if (_delayRemoveBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + { + _delayRemoveBodies->removeObject(body); + return; + } + + if (_info->isLocked()) + { + if (_delayAddBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + { + _delayAddBodies->addObject(body); + _delayDirty = true; + } + }else + { + doAddBody(body); + } +} + +void PhysicsWorld::updateBodies() +{ + if (_info->isLocked()) + { + return; + } + + for (auto body : *_delayAddBodies) + { + doAddBody(dynamic_cast(body)); + } + + for (auto body : *_delayRemoveBodies) + { + doRemoveBody(dynamic_cast(body)); + } + + _delayAddBodies->removeAllObjects(); + _delayRemoveBodies->removeAllObjects(); +} + +void PhysicsWorld::removeBody(int tag) +{ + for (Object* obj : *_bodies) + { + PhysicsBody* body = dynamic_cast(obj); + if (body->getTag() == tag) + { + removeBody(body); + return; + } + } +} + +void PhysicsWorld::removeBody(PhysicsBody* body) +{ + + if (body->getWorld() != this) + { + CCLOG("Physics Warnning: this body doesn't belong to this world"); + return; + } + + // destory the body's joints + for (auto joint : body->_joints) + { + // set destroy param to false to keep the iterator available + removeJoint(joint, false); + + PhysicsBody* other = (joint->getBodyA() == body ? joint->getBodyB() : body); + other->removeJoint(joint); + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } + + body->_joints.clear(); + + removeBodyOrDelay(body); + _bodies->removeObject(body); + body->_world = nullptr; +} + + +void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) +{ + if (_delayAddBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + { + _delayAddBodies->removeObject(body); + return; + } + + if (_info->isLocked()) + { + if (_delayRemoveBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + { + _delayRemoveBodies->addObject(body); + _delayDirty = true; + } + }else + { + doRemoveBody(body); + } +} + PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) @@ -1072,8 +1077,6 @@ PhysicsWorld::~PhysicsWorld() CC_SAFE_DELETE(_debugDraw); } - - PhysicsDebugDraw::PhysicsDebugDraw(PhysicsWorld& world) : _drawNode(nullptr) , _world(world) diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h index f04076ffcf..c8af764432 100644 --- a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h @@ -27,14 +27,23 @@ #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - #include "CCPlatformMacros.h" +#include "Box2D.h" NS_CC_BEGIN class PhysicsBodyInfo { public: + inline b2BodyDef& getBodyDef() { return _bodyDef; } + inline b2Body* getBody() { return _body; } + inline void setBody(b2Body* body) { _body = body; } + +private: + b2Body* _body; + b2BodyDef _bodyDef; + +private: PhysicsBodyInfo(); ~PhysicsBodyInfo(); }; diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp index 4edb6ce3a2..6efc851e3e 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp @@ -25,9 +25,10 @@ #include "CCPhysicsContactInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#include "CCPhysicsContact.h" NS_CC_BEGIN -PhysicsContactInfo::PhysicsContactInfo() +PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) { } diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h index d66ed0e131..791a411f32 100644 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h @@ -30,11 +30,12 @@ #include "CCPlatformMacros.h" NS_CC_BEGIN +class PhysicsContact; class PhysicsContactInfo { public: - PhysicsContactInfo(); + PhysicsContactInfo(PhysicsContact* contact); ~PhysicsContactInfo(); }; diff --git a/cocos/physics/box2d/CCPhysicsHelper_box2d.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h index f14fcef36f..8efa099a96 100644 --- a/cocos/physics/box2d/CCPhysicsHelper_box2d.h +++ b/cocos/physics/box2d/CCPhysicsHelper_box2d.h @@ -27,6 +27,7 @@ #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#include "Box2D.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" @@ -34,6 +35,9 @@ NS_CC_BEGIN class PhysicsHelper { +public: + static b2Vec2 point2Vec2(const Point& point) { return b2Vec2(point.x, point.y); } + static Point vec22Point(const b2Vec2& vec) { return Point(vec.x, vec.y); } }; NS_CC_END diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp index a0b6363cde..27f4aaacbb 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp @@ -25,9 +25,11 @@ #include "CCPhysicsJointInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#include "CCPhysicsJoint.h" + NS_CC_BEGIN -PhysicsJointInfo::PhysicsJointInfo() +PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) { } diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h index e1404eec45..719126886a 100644 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h @@ -31,10 +31,12 @@ #include "CCPlatformMacros.h" NS_CC_BEGIN +class PhysicsJoint; + class PhysicsJointInfo { public: - PhysicsJointInfo(); + PhysicsJointInfo(PhysicsJoint* joint); ~PhysicsJointInfo(); }; diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp index fc3aa61491..4fad8d15b5 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp @@ -25,9 +25,10 @@ #include "CCPhysicsShapeInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#include "CCPhysicsShape.h" NS_CC_BEGIN -PhysicsShapeInfo::PhysicsShapeInfo() +PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) { } diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h index 15720797e0..bf3bcd4262 100644 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h @@ -27,15 +27,18 @@ #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - #include "CCPlatformMacros.h" NS_CC_BEGIN +class PhysicsShape; class PhysicsShapeInfo { public: - PhysicsShapeInfo(); + PhysicsShapeInfo(PhysicsShape* shape); ~PhysicsShapeInfo(); + +public: + PhysicsShape* shape; }; NS_CC_END diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp index fbe3be06d4..22235293b9 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp @@ -25,14 +25,42 @@ #include "CCPhysicsWorldInfo_box2d.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) +#include "CCPhysicsHelper_box2d.h" +#include "CCPhysicsBodyInfo_box2d.h" NS_CC_BEGIN PhysicsWorldInfo::PhysicsWorldInfo() { + _world = new b2World(b2Vec2(0.0f, 0.0f)); } PhysicsWorldInfo::~PhysicsWorldInfo() { + CC_SAFE_DELETE(_world); +} + +void PhysicsWorldInfo::setGravity(const Vect& gravity) +{ + _world->SetGravity(PhysicsHelper::point2Vec2(gravity)); +} + +void PhysicsWorldInfo::addBody(PhysicsBodyInfo& body) +{ + if (body.getBody() != nullptr) + { + removeBody(body); + } + + body.setBody(_world->CreateBody(&body.getBodyDef())); +} + +void PhysicsWorldInfo::removeBody(PhysicsBodyInfo& body) +{ + if (body.getBody() != nullptr) + { + _world->DestroyBody(body.getBody()); + body.setBody(nullptr); + } } NS_CC_END diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index fac9fd5181..dbbfa5c0ab 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -27,15 +27,28 @@ #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - +#include "Box2D.h" #include "CCPlatformMacros.h" NS_CC_BEGIN +class PhysicsBodyInfo; class PhysicsWorldInfo { public: + void setGravity(const Vect& gravity); + inline b2World* getWorld() { return _world; } + void addBody(PhysicsBodyInfo& body); + void removeBody(PhysicsBodyInfo& body); + inline bool isLocked() { return _world->IsLocked(); } + +private: + b2World* _world; + +private: PhysicsWorldInfo(); ~PhysicsWorldInfo(); + + friend class PhysicsWorld; }; NS_CC_END diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index a12e473ec1..dbff438cb7 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -24,6 +24,8 @@ #include "CCPhysicsWorldInfo_chipmunk.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#include "CCPhysicsHelper_chipmunk.h" +#include "CCPhysicsBodyInfo_chipmunk.h" NS_CC_BEGIN #define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ @@ -38,7 +40,6 @@ void PhysicsWorldInfo::remove##name(cp##type* data) \ } \ PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) -PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Body, Body) PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) PhysicsWorldInfo::PhysicsWorldInfo() @@ -51,5 +52,18 @@ PhysicsWorldInfo::~PhysicsWorldInfo() cpSpaceFree(_space); } +void PhysicsWorldInfo::setGravity(const Vect& gravity) +{ + cpSpaceSetGravity(_space, PhysicsHelper::point2cpv(gravity)); +} + +void PhysicsWorldInfo::addBody(PhysicsBodyInfo& body) +{ + if (cpSpaceContainsBody(_space, body.getBody())) + { + cpSpaceAddBody(_space, body.getBody()); + } +} + NS_CC_END #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 0c098d3d90..3b0a2f0eed 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -28,21 +28,25 @@ #include "../CCPhysicsSetting.h" #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#include #include "chipmunk.h" #include "CCPlatformMacros.h" -#include +#include "CCGeometry.h" NS_CC_BEGIN +class PhysicsBodyInfo; class PhysicsWorldInfo { public: - cpSpace* getSpace() const { return _space; } + cpSpace* getWorld() const { return _space; } void addShape(cpShape* shape); void removeShape(cpShape* shape); - void addBody(cpBody* body); - void removeBody(cpBody* body); + void addBody(PhysicsBodyInfo& body); + void removeBody(PhysicsBodyInfo& body); void addJoint(cpConstraint* joint); void removeJoint(cpConstraint* joint); + void setGravity(const Vect& gravity); + inline bool isLocked() { return static_cast(_space->locked_private); } private: PhysicsWorldInfo(); From e55c81c9b6b09d2cf2ec577fe7caf1d0716eea6d Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 25 Nov 2013 14:50:11 +0800 Subject: [PATCH 28/75] upgrade box2d from 2.2.1 to 2.3.0 --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- external/Box2D/Android.mk | 1 + external/Box2D/Box2D.h | 3 +- external/Box2D/CMakeLists.txt | 260 ++- .../Box2D/Collision/Shapes/b2ChainShape.cpp | 201 +- .../Box2D/Collision/Shapes/b2ChainShape.h | 92 +- .../Box2D/Collision/Shapes/b2CircleShape.cpp | 87 +- .../Box2D/Collision/Shapes/b2CircleShape.h | 68 +- .../Box2D/Collision/Shapes/b2EdgeShape.cpp | 147 +- external/Box2D/Collision/Shapes/b2EdgeShape.h | 60 +- .../Box2D/Collision/Shapes/b2PolygonShape.cpp | 604 ++--- .../Box2D/Collision/Shapes/b2PolygonShape.h | 90 +- external/Box2D/Collision/Shapes/b2Shape.h | 94 +- external/Box2D/Collision/b2BroadPhase.cpp | 117 +- external/Box2D/Collision/b2BroadPhase.h | 257 ++- external/Box2D/Collision/b2CollideCircle.cpp | 220 +- external/Box2D/Collision/b2CollideEdge.cpp | 1246 +++++------ external/Box2D/Collision/b2CollidePolygon.cpp | 412 ++-- external/Box2D/Collision/b2Collision.cpp | 357 +-- external/Box2D/Collision/b2Collision.h | 235 +- external/Box2D/Collision/b2Distance.cpp | 906 ++++---- external/Box2D/Collision/b2Distance.h | 116 +- external/Box2D/Collision/b2DynamicTree.cpp | 1139 +++++----- external/Box2D/Collision/b2DynamicTree.h | 355 +-- external/Box2D/Collision/b2TimeOfImpact.cpp | 742 +++--- external/Box2D/Collision/b2TimeOfImpact.h | 30 +- external/Box2D/Common/b2BlockAllocator.cpp | 279 ++- external/Box2D/Common/b2BlockAllocator.h | 28 +- external/Box2D/Common/b2Draw.cpp | 10 +- external/Box2D/Common/b2Draw.h | 83 +- external/Box2D/Common/b2GrowableStack.h | 90 +- external/Box2D/Common/b2Math.cpp | 92 +- external/Box2D/Common/b2Math.h | 758 +++---- external/Box2D/Common/b2Settings.cpp | 33 +- external/Box2D/Common/b2Settings.h | 61 +- external/Box2D/Common/b2StackAllocator.cpp | 78 +- external/Box2D/Common/b2StackAllocator.h | 30 +- external/Box2D/Common/b2Timer.cpp | 49 +- external/Box2D/Common/b2Timer.h | 25 +- .../Contacts/b2ChainAndCircleContact.cpp | 23 +- .../Contacts/b2ChainAndCircleContact.h | 12 +- .../Contacts/b2ChainAndPolygonContact.cpp | 23 +- .../Contacts/b2ChainAndPolygonContact.h | 12 +- .../Dynamics/Contacts/b2CircleContact.cpp | 21 +- .../Box2D/Dynamics/Contacts/b2CircleContact.h | 12 +- .../Box2D/Dynamics/Contacts/b2Contact.cpp | 301 +-- external/Box2D/Dynamics/Contacts/b2Contact.h | 292 +-- .../Dynamics/Contacts/b2ContactSolver.cpp | 1235 +++++----- .../Box2D/Dynamics/Contacts/b2ContactSolver.h | 83 +- .../Contacts/b2EdgeAndCircleContact.cpp | 19 +- .../Contacts/b2EdgeAndCircleContact.h | 12 +- .../Contacts/b2EdgeAndPolygonContact.cpp | 19 +- .../Contacts/b2EdgeAndPolygonContact.h | 12 +- .../Contacts/b2PolygonAndCircleContact.cpp | 19 +- .../Contacts/b2PolygonAndCircleContact.h | 10 +- .../Dynamics/Contacts/b2PolygonContact.cpp | 21 +- .../Dynamics/Contacts/b2PolygonContact.h | 12 +- .../Box2D/Dynamics/Joints/b2DistanceJoint.cpp | 308 +-- .../Box2D/Dynamics/Joints/b2DistanceJoint.h | 162 +- .../Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 262 +-- .../Box2D/Dynamics/Joints/b2FrictionJoint.h | 124 +- .../Box2D/Dynamics/Joints/b2GearJoint.cpp | 570 +++-- external/Box2D/Dynamics/Joints/b2GearJoint.h | 120 +- external/Box2D/Dynamics/Joints/b2Joint.cpp | 260 ++- external/Box2D/Dynamics/Joints/b2Joint.h | 202 +- .../Box2D/Dynamics/Joints/b2MotorJoint.cpp | 304 +++ external/Box2D/Dynamics/Joints/b2MotorJoint.h | 133 ++ .../Box2D/Dynamics/Joints/b2MouseJoint.cpp | 207 +- external/Box2D/Dynamics/Joints/b2MouseJoint.h | 133 +- .../Dynamics/Joints/b2PrismaticJoint.cpp | 785 ++++--- .../Box2D/Dynamics/Joints/b2PrismaticJoint.h | 228 +- .../Box2D/Dynamics/Joints/b2PulleyJoint.cpp | 410 ++-- .../Box2D/Dynamics/Joints/b2PulleyJoint.h | 163 +- .../Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | 660 +++--- .../Box2D/Dynamics/Joints/b2RevoluteJoint.h | 226 +- .../Box2D/Dynamics/Joints/b2RopeJoint.cpp | 276 +-- external/Box2D/Dynamics/Joints/b2RopeJoint.h | 108 +- .../Box2D/Dynamics/Joints/b2WeldJoint.cpp | 400 ++-- external/Box2D/Dynamics/Joints/b2WeldJoint.h | 136 +- .../Box2D/Dynamics/Joints/b2WheelJoint.cpp | 514 ++--- external/Box2D/Dynamics/Joints/b2WheelJoint.h | 216 +- external/Box2D/Dynamics/b2Body.cpp | 769 ++++--- external/Box2D/Dynamics/b2Body.h | 986 ++++---- external/Box2D/Dynamics/b2ContactManager.cpp | 415 ++-- external/Box2D/Dynamics/b2ContactManager.h | 24 +- external/Box2D/Dynamics/b2Fixture.cpp | 406 ++-- external/Box2D/Dynamics/b2Fixture.h | 316 +-- external/Box2D/Dynamics/b2Island.cpp | 624 +++--- external/Box2D/Dynamics/b2Island.h | 84 +- external/Box2D/Dynamics/b2TimeStep.h | 42 +- external/Box2D/Dynamics/b2World.cpp | 1989 +++++++++-------- external/Box2D/Dynamics/b2World.h | 377 ++-- external/Box2D/Dynamics/b2WorldCallbacks.cpp | 16 +- external/Box2D/Dynamics/b2WorldCallbacks.h | 126 +- external/Box2D/Rope/b2Rope.cpp | 336 +-- external/Box2D/Rope/b2Rope.h | 114 +- .../Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp | 652 +++--- .../Cpp/TestCpp/Classes/Box2DTestBed/Test.h | 223 +- .../Classes/Box2DTestBed/TestEntries.cpp | 108 +- .../Classes/Box2DTestBed/Tests/AddPair.h | 93 +- .../Classes/Box2DTestBed/Tests/ApplyForce.h | 246 +- .../Classes/Box2DTestBed/Tests/BodyTypes.h | 214 +- .../Classes/Box2DTestBed/Tests/Breakable.h | 206 +- .../Classes/Box2DTestBed/Tests/Bridge.h | 158 +- .../Classes/Box2DTestBed/Tests/BulletTest.h | 170 +- .../Classes/Box2DTestBed/Tests/Cantilever.h | 288 +-- .../TestCpp/Classes/Box2DTestBed/Tests/Car.h | 416 ++-- .../Classes/Box2DTestBed/Tests/Chain.h | 78 +- .../Box2DTestBed/Tests/CharacterCollision.h | 374 ++-- .../Box2DTestBed/Tests/CollisionFiltering.h | 215 +- .../Box2DTestBed/Tests/CollisionProcessing.h | 252 +-- .../Box2DTestBed/Tests/CompoundShapes.h | 192 +- .../Classes/Box2DTestBed/Tests/Confined.h | 228 +- .../Box2DTestBed/Tests/ContinuousTest.h | 194 +- .../Classes/Box2DTestBed/Tests/ConvexHull.h | 116 + .../Classes/Box2DTestBed/Tests/ConveyorBelt.h | 98 + .../Classes/Box2DTestBed/Tests/DistanceTest.h | 174 +- .../Classes/Box2DTestBed/Tests/Dominos.h | 302 +-- .../Classes/Box2DTestBed/Tests/DumpShell.h | 360 ++- .../Box2DTestBed/Tests/DynamicTreeTest.h | 544 ++--- .../Classes/Box2DTestBed/Tests/EdgeShapes.h | 356 +-- .../Classes/Box2DTestBed/Tests/EdgeTest.h | 132 +- .../Classes/Box2DTestBed/Tests/Gears.h | 267 ++- .../Classes/Box2DTestBed/Tests/Mobile.h | 102 + .../Box2DTestBed/Tests/MobileBalanced.h | 105 + .../Classes/Box2DTestBed/Tests/MotorJoint.h | 114 + .../Box2DTestBed/Tests/OneSidedPlatform.h | 156 +- .../Classes/Box2DTestBed/Tests/Pinball.h | 230 +- .../Box2DTestBed/Tests/PolyCollision.h | 152 +- .../Classes/Box2DTestBed/Tests/PolyShapes.h | 434 ++-- .../Classes/Box2DTestBed/Tests/Prismatic.h | 130 +- .../Classes/Box2DTestBed/Tests/Pulleys.h | 124 +- .../Classes/Box2DTestBed/Tests/Pyramid.h | 100 +- .../Classes/Box2DTestBed/Tests/RayCast.h | 703 +++--- .../Classes/Box2DTestBed/Tests/Revolute.h | 224 +- .../TestCpp/Classes/Box2DTestBed/Tests/Rope.h | 118 +- .../Classes/Box2DTestBed/Tests/RopeJoint.h | 186 +- .../Classes/Box2DTestBed/Tests/SensorTest.h | 252 +-- .../Classes/Box2DTestBed/Tests/ShapeEditing.h | 132 +- .../Classes/Box2DTestBed/Tests/SliderCrank.h | 208 +- .../Classes/Box2DTestBed/Tests/SphereStack.h | 90 +- .../Classes/Box2DTestBed/Tests/TheoJansen.h | 360 +-- .../Classes/Box2DTestBed/Tests/Tiles.h | 212 +- .../Classes/Box2DTestBed/Tests/TimeOfImpact.h | 162 +- .../Classes/Box2DTestBed/Tests/Tumbler.h | 120 +- .../Box2DTestBed/Tests/VaryingFriction.h | 148 +- .../Box2DTestBed/Tests/VaryingRestitution.h | 62 +- .../Box2DTestBed/Tests/VerticalStack.h | 220 +- .../TestCpp/Classes/Box2DTestBed/Tests/Web.h | 316 +-- 150 files changed, 19124 insertions(+), 17820 deletions(-) create mode 100644 external/Box2D/Dynamics/Joints/b2MotorJoint.cpp create mode 100644 external/Box2D/Dynamics/Joints/b2MotorJoint.h create mode 100644 samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h create mode 100644 samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h create mode 100644 samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h create mode 100644 samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h create mode 100644 samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 507d392456..6392a6b63e 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -0d9ce76f7e63d75718c38b1137b2580e19d0db76 \ No newline at end of file +5d37163416155a0050b068b30de3aabc6e0b4013 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index fe0929b0b5..a1b5294787 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2461d13fd6f4fadc6ee396109932e50b1de8ed99 \ No newline at end of file +1e608aab69f45820f3120339ca3d1610a8a60a7f \ No newline at end of file diff --git a/external/Box2D/Android.mk b/external/Box2D/Android.mk index c366750c01..ca6cfca39e 100644 --- a/external/Box2D/Android.mk +++ b/external/Box2D/Android.mk @@ -44,6 +44,7 @@ Dynamics/Joints/b2DistanceJoint.cpp \ Dynamics/Joints/b2FrictionJoint.cpp \ Dynamics/Joints/b2GearJoint.cpp \ Dynamics/Joints/b2Joint.cpp \ +Dynamics/Joints/b2MotorJoint.cpp \ Dynamics/Joints/b2MouseJoint.cpp \ Dynamics/Joints/b2PrismaticJoint.cpp \ Dynamics/Joints/b2PulleyJoint.cpp \ diff --git a/external/Box2D/Box2D.h b/external/Box2D/Box2D.h index f674d82269..187046131d 100644 --- a/external/Box2D/Box2D.h +++ b/external/Box2D/Box2D.h @@ -56,12 +56,13 @@ For discussion please visit http://box2d.org/forum #include #include #include -#include +#include #include #include #include #include #include #include +#include #endif diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt index fd1f63dc64..b800bcccbc 100644 --- a/external/Box2D/CMakeLists.txt +++ b/external/Box2D/CMakeLists.txt @@ -1,61 +1,207 @@ -set(BOX2D_SRC - Collision/Shapes/b2ChainShape.cpp - Collision/Shapes/b2CircleShape.cpp - Collision/Shapes/b2EdgeShape.cpp - Collision/Shapes/b2PolygonShape.cpp - Collision/b2BroadPhase.cpp - Collision/b2CollideCircle.cpp - Collision/b2CollideEdge.cpp - Collision/b2CollidePolygon.cpp - Collision/b2Collision.cpp - Collision/b2Distance.cpp - Collision/b2DynamicTree.cpp - Collision/b2TimeOfImpact.cpp - Common/b2BlockAllocator.cpp - Common/b2Draw.cpp - Common/b2Math.cpp - Common/b2Settings.cpp - Common/b2StackAllocator.cpp - Common/b2Timer.cpp - Dynamics/Contacts/b2ChainAndCircleContact.cpp - Dynamics/Contacts/b2ChainAndPolygonContact.cpp - Dynamics/Contacts/b2CircleContact.cpp - Dynamics/Contacts/b2Contact.cpp - Dynamics/Contacts/b2ContactSolver.cpp - Dynamics/Contacts/b2EdgeAndCircleContact.cpp - Dynamics/Contacts/b2EdgeAndPolygonContact.cpp - Dynamics/Contacts/b2PolygonAndCircleContact.cpp - Dynamics/Contacts/b2PolygonContact.cpp - Dynamics/Joints/b2DistanceJoint.cpp - Dynamics/Joints/b2FrictionJoint.cpp - Dynamics/Joints/b2GearJoint.cpp - Dynamics/Joints/b2Joint.cpp - Dynamics/Joints/b2MouseJoint.cpp - Dynamics/Joints/b2PrismaticJoint.cpp - Dynamics/Joints/b2PulleyJoint.cpp - Dynamics/Joints/b2RevoluteJoint.cpp - Dynamics/Joints/b2RopeJoint.cpp - Dynamics/Joints/b2WeldJoint.cpp - Dynamics/Joints/b2WheelJoint.cpp - Dynamics/b2Body.cpp - Dynamics/b2ContactManager.cpp - Dynamics/b2Fixture.cpp - Dynamics/b2Island.cpp - Dynamics/b2World.cpp - Dynamics/b2WorldCallbacks.cpp - Rope/b2Rope.cpp +set(BOX2D_Collision_SRCS + Collision/b2BroadPhase.cpp + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Distance.cpp + Collision/b2DynamicTree.cpp + Collision/b2TimeOfImpact.cpp ) +set(BOX2D_Collision_HDRS + Collision/b2BroadPhase.h + Collision/b2Collision.h + Collision/b2Distance.h + Collision/b2DynamicTree.h + Collision/b2TimeOfImpact.h +) +set(BOX2D_Shapes_SRCS + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2PolygonShape.cpp +) +set(BOX2D_Shapes_HDRS + Collision/Shapes/b2CircleShape.h + Collision/Shapes/b2EdgeShape.h + Collision/Shapes/b2ChainShape.h + Collision/Shapes/b2PolygonShape.h + Collision/Shapes/b2Shape.h +) +set(BOX2D_Common_SRCS + Common/b2BlockAllocator.cpp + Common/b2Draw.cpp + Common/b2Math.cpp + Common/b2Settings.cpp + Common/b2StackAllocator.cpp + Common/b2Timer.cpp +) +set(BOX2D_Common_HDRS + Common/b2BlockAllocator.h + Common/b2Draw.h + Common/b2GrowableStack.h + Common/b2Math.h + Common/b2Settings.h + Common/b2StackAllocator.h + Common/b2Timer.h +) +set(BOX2D_Dynamics_SRCS + Dynamics/b2Body.cpp + Dynamics/b2ContactManager.cpp + Dynamics/b2Fixture.cpp + Dynamics/b2Island.cpp + Dynamics/b2World.cpp + Dynamics/b2WorldCallbacks.cpp +) +set(BOX2D_Dynamics_HDRS + Dynamics/b2Body.h + Dynamics/b2ContactManager.h + Dynamics/b2Fixture.h + Dynamics/b2Island.h + Dynamics/b2TimeStep.h + Dynamics/b2World.h + Dynamics/b2WorldCallbacks.h +) +set(BOX2D_Contacts_SRCS + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2PolygonContact.cpp +) +set(BOX2D_Contacts_HDRS + Dynamics/Contacts/b2CircleContact.h + Dynamics/Contacts/b2Contact.h + Dynamics/Contacts/b2ContactSolver.h + Dynamics/Contacts/b2PolygonAndCircleContact.h + Dynamics/Contacts/b2EdgeAndCircleContact.h + Dynamics/Contacts/b2EdgeAndPolygonContact.h + Dynamics/Contacts/b2ChainAndCircleContact.h + Dynamics/Contacts/b2ChainAndPolygonContact.h + Dynamics/Contacts/b2PolygonContact.h +) +set(BOX2D_Joints_SRCS + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2MotorJoint.cpp + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WheelJoint.cpp +) +set(BOX2D_Joints_HDRS + Dynamics/Joints/b2DistanceJoint.h + Dynamics/Joints/b2FrictionJoint.h + Dynamics/Joints/b2GearJoint.h + Dynamics/Joints/b2Joint.h + Dynamics/Joints/b2MotorJoint.h + Dynamics/Joints/b2MouseJoint.h + Dynamics/Joints/b2PrismaticJoint.h + Dynamics/Joints/b2PulleyJoint.h + Dynamics/Joints/b2RevoluteJoint.h + Dynamics/Joints/b2RopeJoint.h + Dynamics/Joints/b2WeldJoint.h + Dynamics/Joints/b2WheelJoint.h +) +set(BOX2D_Rope_SRCS + Rope/b2Rope.cpp +) +set(BOX2D_Rope_HDRS + Rope/b2Rope.h +) +set(BOX2D_General_HDRS + Box2D.h +) +include_directories( ../ ) -include_directories( - .. -) +if(BOX2D_BUILD_SHARED) + add_library(Box2D_shared SHARED + ${BOX2D_General_HDRS} + ${BOX2D_Joints_SRCS} + ${BOX2D_Joints_HDRS} + ${BOX2D_Contacts_SRCS} + ${BOX2D_Contacts_HDRS} + ${BOX2D_Dynamics_SRCS} + ${BOX2D_Dynamics_HDRS} + ${BOX2D_Common_SRCS} + ${BOX2D_Common_HDRS} + ${BOX2D_Shapes_SRCS} + ${BOX2D_Shapes_HDRS} + ${BOX2D_Collision_SRCS} + ${BOX2D_Collision_HDRS} + ${BOX2D_Rope_SRCS} + ${BOX2D_Rope_HDRS} + ) + set_target_properties(Box2D_shared PROPERTIES + OUTPUT_NAME "Box2D" + CLEAN_DIRECT_OUTPUT 1 + VERSION ${BOX2D_VERSION} + ) +endif() -add_library(box2d STATIC - ${BOX2D_SRC} -) +if(BOX2D_BUILD_STATIC) + add_library(Box2D STATIC + ${BOX2D_General_HDRS} + ${BOX2D_Joints_SRCS} + ${BOX2D_Joints_HDRS} + ${BOX2D_Contacts_SRCS} + ${BOX2D_Contacts_HDRS} + ${BOX2D_Dynamics_SRCS} + ${BOX2D_Dynamics_HDRS} + ${BOX2D_Common_SRCS} + ${BOX2D_Common_HDRS} + ${BOX2D_Shapes_SRCS} + ${BOX2D_Shapes_HDRS} + ${BOX2D_Collision_SRCS} + ${BOX2D_Collision_HDRS} + ${BOX2D_Rope_SRCS} + ${BOX2D_Rope_HDRS} + ) + set_target_properties(Box2D PROPERTIES + CLEAN_DIRECT_OUTPUT 1 + VERSION ${BOX2D_VERSION} + ) +endif() -set_target_properties(box2d - PROPERTIES - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" -) +# These are used to create visual studio folders. +source_group(Collision FILES ${BOX2D_Collision_SRCS} ${BOX2D_Collision_HDRS}) +source_group(Collision\\Shapes FILES ${BOX2D_Shapes_SRCS} ${BOX2D_Shapes_HDRS}) +source_group(Common FILES ${BOX2D_Common_SRCS} ${BOX2D_Common_HDRS}) +source_group(Dynamics FILES ${BOX2D_Dynamics_SRCS} ${BOX2D_Dynamics_HDRS}) +source_group(Dynamics\\Contacts FILES ${BOX2D_Contacts_SRCS} ${BOX2D_Contacts_HDRS}) +source_group(Dynamics\\Joints FILES ${BOX2D_Joints_SRCS} ${BOX2D_Joints_HDRS}) +source_group(Include FILES ${BOX2D_General_HDRS}) +source_group(Rope FILES ${BOX2D_Rope_SRCS} ${BOX2D_Rope_HDRS}) + +if(BOX2D_INSTALL) + # install headers + install(FILES ${BOX2D_General_HDRS} DESTINATION include/Box2D) + install(FILES ${BOX2D_Collision_HDRS} DESTINATION include/Box2D/Collision) + install(FILES ${BOX2D_Shapes_HDRS} DESTINATION include/Box2D/Collision/Shapes) + install(FILES ${BOX2D_Common_HDRS} DESTINATION include/Box2D/Common) + install(FILES ${BOX2D_Dynamics_HDRS} DESTINATION include/Box2D/Dynamics) + install(FILES ${BOX2D_Contacts_HDRS} DESTINATION include/Box2D/Dynamics/Contacts) + install(FILES ${BOX2D_Joints_HDRS} DESTINATION include/Box2D/Dynamics/Joints) + install(FILES ${BOX2D_Rope_HDRS} DESTINATION include/Box2D/Rope) + + # install libraries + if(BOX2D_BUILD_SHARED) + install(TARGETS Box2D_shared EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}) + endif() + if(BOX2D_BUILD_STATIC) + install(TARGETS Box2D EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}) + endif() + + # install build system hooks for third-party apps + install(EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}/Box2D) + install(FILES Box2DConfig.cmake DESTINATION ${LIB_INSTALL_DIR}/Box2D) +endif(BOX2D_INSTALL) diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.cpp b/external/Box2D/Collision/Shapes/b2ChainShape.cpp index 79b4304b5b..069b4cae84 100644 --- a/external/Box2D/Collision/Shapes/b2ChainShape.cpp +++ b/external/Box2D/Collision/Shapes/b2ChainShape.cpp @@ -19,153 +19,172 @@ #include #include #include -#include -using namespace std; +#include b2ChainShape::~b2ChainShape() { - b2Free(m_vertices); - m_vertices = NULL; - m_count = 0; + b2Free(m_vertices); + m_vertices = NULL; + m_count = 0; } void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) { - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 3); - m_count = count + 1; - m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); - m_vertices[count] = m_vertices[0]; - m_prevVertex = m_vertices[m_count - 2]; - m_nextVertex = m_vertices[1]; - m_hasPrevVertex = true; - m_hasNextVertex = true; + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 3); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v1 = vertices[i-1]; + b2Vec2 v2 = vertices[i]; + // If the code crashes here, it means your vertices are too close together. + b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop); + } + + m_count = count + 1; + m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); + m_vertices[count] = m_vertices[0]; + m_prevVertex = m_vertices[m_count - 2]; + m_nextVertex = m_vertices[1]; + m_hasPrevVertex = true; + m_hasNextVertex = true; } void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) { - b2Assert(m_vertices == NULL && m_count == 0); - b2Assert(count >= 2); - m_count = count; - m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); - m_hasPrevVertex = false; - m_hasNextVertex = false; + b2Assert(m_vertices == NULL && m_count == 0); + b2Assert(count >= 2); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v1 = vertices[i-1]; + b2Vec2 v2 = vertices[i]; + // If the code crashes here, it means your vertices are too close together. + b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop); + } + + m_count = count; + m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); + memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); + + m_hasPrevVertex = false; + m_hasNextVertex = false; + + m_prevVertex.SetZero(); + m_nextVertex.SetZero(); } void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) { - m_prevVertex = prevVertex; - m_hasPrevVertex = true; + m_prevVertex = prevVertex; + m_hasPrevVertex = true; } void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) { - m_nextVertex = nextVertex; - m_hasNextVertex = true; + m_nextVertex = nextVertex; + m_hasNextVertex = true; } b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const { - void* mem = allocator->Allocate(sizeof(b2ChainShape)); - b2ChainShape* clone = new (mem) b2ChainShape; - clone->CreateChain(m_vertices, m_count); - clone->m_prevVertex = m_prevVertex; - clone->m_nextVertex = m_nextVertex; - clone->m_hasPrevVertex = m_hasPrevVertex; - clone->m_hasNextVertex = m_hasNextVertex; - return clone; + void* mem = allocator->Allocate(sizeof(b2ChainShape)); + b2ChainShape* clone = new (mem) b2ChainShape; + clone->CreateChain(m_vertices, m_count); + clone->m_prevVertex = m_prevVertex; + clone->m_nextVertex = m_nextVertex; + clone->m_hasPrevVertex = m_hasPrevVertex; + clone->m_hasNextVertex = m_hasNextVertex; + return clone; } int32 b2ChainShape::GetChildCount() const { - // edge count = vertex count - 1 - return m_count - 1; + // edge count = vertex count - 1 + return m_count - 1; } void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const { - b2Assert(0 <= index && index < m_count - 1); - edge->m_type = b2Shape::e_edge; - edge->m_radius = m_radius; + b2Assert(0 <= index && index < m_count - 1); + edge->m_type = b2Shape::e_edge; + edge->m_radius = m_radius; - edge->m_vertex1 = m_vertices[index + 0]; - edge->m_vertex2 = m_vertices[index + 1]; + edge->m_vertex1 = m_vertices[index + 0]; + edge->m_vertex2 = m_vertices[index + 1]; - if (index > 0) - { - edge->m_vertex0 = m_vertices[index - 1]; - edge->m_hasVertex0 = true; - } - else - { - edge->m_vertex0 = m_prevVertex; - edge->m_hasVertex0 = m_hasPrevVertex; - } + if (index > 0) + { + edge->m_vertex0 = m_vertices[index - 1]; + edge->m_hasVertex0 = true; + } + else + { + edge->m_vertex0 = m_prevVertex; + edge->m_hasVertex0 = m_hasPrevVertex; + } - if (index < m_count - 2) - { - edge->m_vertex3 = m_vertices[index + 2]; - edge->m_hasVertex3 = true; - } - else - { - edge->m_vertex3 = m_nextVertex; - edge->m_hasVertex3 = m_hasNextVertex; - } + if (index < m_count - 2) + { + edge->m_vertex3 = m_vertices[index + 2]; + edge->m_hasVertex3 = true; + } + else + { + edge->m_vertex3 = m_nextVertex; + edge->m_hasVertex3 = m_hasNextVertex; + } } bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; } bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const + const b2Transform& xf, int32 childIndex) const { - b2Assert(childIndex < m_count); + b2Assert(childIndex < m_count); - b2EdgeShape edgeShape; + b2EdgeShape edgeShape; - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } - edgeShape.m_vertex1 = m_vertices[i1]; - edgeShape.m_vertex2 = m_vertices[i2]; + edgeShape.m_vertex1 = m_vertices[i1]; + edgeShape.m_vertex2 = m_vertices[i2]; - return edgeShape.RayCast(output, input, xf, 0); + return edgeShape.RayCast(output, input, xf, 0); } void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { - b2Assert(childIndex < m_count); + b2Assert(childIndex < m_count); - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } + int32 i1 = childIndex; + int32 i2 = childIndex + 1; + if (i2 == m_count) + { + i2 = 0; + } - b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); - b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); + b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); + b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); - aabb->lowerBound = b2Min(v1, v2); - aabb->upperBound = b2Max(v1, v2); + aabb->lowerBound = b2Min(v1, v2); + aabb->upperBound = b2Max(v1, v2); } void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const { - B2_NOT_USED(density); + B2_NOT_USED(density); - massData->mass = 0.0f; - massData->center.SetZero(); - massData->I = 0.0f; + massData->mass = 0.0f; + massData->center.SetZero(); + massData->I = 0.0f; } diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.h b/external/Box2D/Collision/Shapes/b2ChainShape.h index 9c9a9eaa7d..e836dfef9a 100644 --- a/external/Box2D/Collision/Shapes/b2ChainShape.h +++ b/external/Box2D/Collision/Shapes/b2ChainShape.h @@ -32,71 +32,71 @@ class b2EdgeShape; class b2ChainShape : public b2Shape { public: - b2ChainShape(); + b2ChainShape(); - /// The destructor frees the vertices using b2Free. - ~b2ChainShape(); + /// The destructor frees the vertices using b2Free. + ~b2ChainShape(); - /// Create a loop. This automatically adjusts connectivity. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateLoop(const b2Vec2* vertices, int32 count); + /// Create a loop. This automatically adjusts connectivity. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateLoop(const b2Vec2* vertices, int32 count); - /// Create a chain with isolated end vertices. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateChain(const b2Vec2* vertices, int32 count); + /// Create a chain with isolated end vertices. + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count + void CreateChain(const b2Vec2* vertices, int32 count); - /// Establish connectivity to a vertex that precedes the first vertex. - /// Don't call this for loops. - void SetPrevVertex(const b2Vec2& prevVertex); + /// Establish connectivity to a vertex that precedes the first vertex. + /// Don't call this for loops. + void SetPrevVertex(const b2Vec2& prevVertex); - /// Establish connectivity to a vertex that follows the last vertex. - /// Don't call this for loops. - void SetNextVertex(const b2Vec2& nextVertex); + /// Establish connectivity to a vertex that follows the last vertex. + /// Don't call this for loops. + void SetNextVertex(const b2Vec2& nextVertex); - /// Implement b2Shape. Vertices are cloned using b2Alloc. - b2Shape* Clone(b2BlockAllocator* allocator) const; + /// Implement b2Shape. Vertices are cloned using b2Alloc. + b2Shape* Clone(b2BlockAllocator* allocator) const; - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; - /// Get a child edge. - void GetChildEdge(b2EdgeShape* edge, int32 index) const; + /// Get a child edge. + void GetChildEdge(b2EdgeShape* edge, int32 index) const; - /// This always return false. - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + /// This always return false. + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - /// Chains have zero mass. - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; + /// Chains have zero mass. + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; - /// The vertices. Owned by this class. - b2Vec2* m_vertices; + /// The vertices. Owned by this class. + b2Vec2* m_vertices; - /// The vertex count. - int32 m_count; + /// The vertex count. + int32 m_count; - b2Vec2 m_prevVertex, m_nextVertex; - bool m_hasPrevVertex, m_hasNextVertex; + b2Vec2 m_prevVertex, m_nextVertex; + bool m_hasPrevVertex, m_hasNextVertex; }; inline b2ChainShape::b2ChainShape() { - m_type = e_chain; - m_radius = b2_polygonRadius; - m_vertices = NULL; - m_count = 0; - m_hasPrevVertex = false; - m_hasNextVertex = false; + m_type = e_chain; + m_radius = b2_polygonRadius; + m_vertices = NULL; + m_count = 0; + m_hasPrevVertex = false; + m_hasNextVertex = false; } #endif diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.cpp b/external/Box2D/Collision/Shapes/b2CircleShape.cpp index 587ca960b2..39d4ae9998 100644 --- a/external/Box2D/Collision/Shapes/b2CircleShape.cpp +++ b/external/Box2D/Collision/Shapes/b2CircleShape.cpp @@ -18,26 +18,25 @@ #include #include -using namespace std; b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const { - void* mem = allocator->Allocate(sizeof(b2CircleShape)); - b2CircleShape* clone = new (mem) b2CircleShape; - *clone = *this; - return clone; + void* mem = allocator->Allocate(sizeof(b2CircleShape)); + b2CircleShape* clone = new (mem) b2CircleShape; + *clone = *this; + return clone; } int32 b2CircleShape::GetChildCount() const { - return 1; + return 1; } bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const { - b2Vec2 center = transform.p + b2Mul(transform.q, m_p); - b2Vec2 d = p - center; - return b2Dot(d, d) <= m_radius * m_radius; + b2Vec2 center = transform.p + b2Mul(transform.q, m_p); + b2Vec2 d = p - center; + return b2Dot(d, d) <= m_radius * m_radius; } // Collision Detection in Interactive 3D Environments by Gino van den Bergen @@ -45,56 +44,56 @@ bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) con // x = s + a * r // norm(x) = radius bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const + const b2Transform& transform, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - b2Vec2 position = transform.p + b2Mul(transform.q, m_p); - b2Vec2 s = input.p1 - position; - float32 b = b2Dot(s, s) - m_radius * m_radius; + b2Vec2 position = transform.p + b2Mul(transform.q, m_p); + b2Vec2 s = input.p1 - position; + float32 b = b2Dot(s, s) - m_radius * m_radius; - // Solve quadratic equation. - b2Vec2 r = input.p2 - input.p1; - float32 c = b2Dot(s, r); - float32 rr = b2Dot(r, r); - float32 sigma = c * c - rr * b; + // Solve quadratic equation. + b2Vec2 r = input.p2 - input.p1; + float32 c = b2Dot(s, r); + float32 rr = b2Dot(r, r); + float32 sigma = c * c - rr * b; - // Check for negative discriminant and short segment. - if (sigma < 0.0f || rr < b2_epsilon) - { - return false; - } + // Check for negative discriminant and short segment. + if (sigma < 0.0f || rr < b2_epsilon) + { + return false; + } - // Find the point of intersection of the line with the circle. - float32 a = -(c + b2Sqrt(sigma)); + // Find the point of intersection of the line with the circle. + float32 a = -(c + b2Sqrt(sigma)); - // Is the intersection point on the segment? - if (0.0f <= a && a <= input.maxFraction * rr) - { - a /= rr; - output->fraction = a; - output->normal = s + a * r; - output->normal.Normalize(); - return true; - } + // Is the intersection point on the segment? + if (0.0f <= a && a <= input.maxFraction * rr) + { + a /= rr; + output->fraction = a; + output->normal = s + a * r; + output->normal.Normalize(); + return true; + } - return false; + return false; } void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - b2Vec2 p = transform.p + b2Mul(transform.q, m_p); - aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); - aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); + b2Vec2 p = transform.p + b2Mul(transform.q, m_p); + aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); + aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); } void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const { - massData->mass = density * b2_pi * m_radius * m_radius; - massData->center = m_p; + massData->mass = density * b2_pi * m_radius * m_radius; + massData->center = m_p; - // inertia about the local origin - massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); + // inertia about the local origin + massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); } diff --git a/external/Box2D/Collision/Shapes/b2CircleShape.h b/external/Box2D/Collision/Shapes/b2CircleShape.h index c4e23a475b..3209f924ad 100644 --- a/external/Box2D/Collision/Shapes/b2CircleShape.h +++ b/external/Box2D/Collision/Shapes/b2CircleShape.h @@ -25,67 +25,67 @@ class b2CircleShape : public b2Shape { public: - b2CircleShape(); + b2CircleShape(); - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; - /// Implement b2Shape. - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + /// Implement b2Shape. + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - /// Get the vertex count. - int32 GetVertexCount() const { return 1; } + /// Get the vertex count. + int32 GetVertexCount() const { return 1; } - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; - /// Position - b2Vec2 m_p; + /// Position + b2Vec2 m_p; }; inline b2CircleShape::b2CircleShape() { - m_type = e_circle; - m_radius = 0.0f; - m_p.SetZero(); + m_type = e_circle; + m_radius = 0.0f; + m_p.SetZero(); } inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const { - B2_NOT_USED(d); - return 0; + B2_NOT_USED(d); + return 0; } inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const { - B2_NOT_USED(d); - return m_p; + B2_NOT_USED(d); + return m_p; } inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const { - B2_NOT_USED(index); - b2Assert(index == 0); - return m_p; + B2_NOT_USED(index); + b2Assert(index == 0); + return m_p; } #endif diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.cpp b/external/Box2D/Collision/Shapes/b2EdgeShape.cpp index 7b09e55bf4..8bcd12f7a7 100644 --- a/external/Box2D/Collision/Shapes/b2EdgeShape.cpp +++ b/external/Box2D/Collision/Shapes/b2EdgeShape.cpp @@ -18,34 +18,33 @@ #include #include -using namespace std; void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) { - m_vertex1 = v1; - m_vertex2 = v2; - m_hasVertex0 = false; - m_hasVertex3 = false; + m_vertex1 = v1; + m_vertex2 = v2; + m_hasVertex0 = false; + m_hasVertex3 = false; } b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const { - void* mem = allocator->Allocate(sizeof(b2EdgeShape)); - b2EdgeShape* clone = new (mem) b2EdgeShape; - *clone = *this; - return clone; + void* mem = allocator->Allocate(sizeof(b2EdgeShape)); + b2EdgeShape* clone = new (mem) b2EdgeShape; + *clone = *this; + return clone; } int32 b2EdgeShape::GetChildCount() const { - return 1; + return 1; } bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; + B2_NOT_USED(xf); + B2_NOT_USED(p); + return false; } // p = p1 + t * d @@ -53,87 +52,87 @@ bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const // p1 + t * d = v1 + s * e // s * e - t * d = p1 - v1 bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const + const b2Transform& xf, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - // Put the ray into the edge's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; + // Put the ray into the edge's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; - b2Vec2 v1 = m_vertex1; - b2Vec2 v2 = m_vertex2; - b2Vec2 e = v2 - v1; - b2Vec2 normal(e.y, -e.x); - normal.Normalize(); + b2Vec2 v1 = m_vertex1; + b2Vec2 v2 = m_vertex2; + b2Vec2 e = v2 - v1; + b2Vec2 normal(e.y, -e.x); + normal.Normalize(); - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float32 numerator = b2Dot(normal, v1 - p1); - float32 denominator = b2Dot(normal, d); + // q = p1 + t * d + // dot(normal, q - v1) = 0 + // dot(normal, p1 - v1) + t * dot(normal, d) = 0 + float32 numerator = b2Dot(normal, v1 - p1); + float32 denominator = b2Dot(normal, d); - if (denominator == 0.0f) - { - return false; - } + if (denominator == 0.0f) + { + return false; + } - float32 t = numerator / denominator; - if (t < 0.0f || input.maxFraction < t) - { - return false; - } + float32 t = numerator / denominator; + if (t < 0.0f || input.maxFraction < t) + { + return false; + } - b2Vec2 q = p1 + t * d; + b2Vec2 q = p1 + t * d; - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - b2Vec2 r = v2 - v1; - float32 rr = b2Dot(r, r); - if (rr == 0.0f) - { - return false; - } + // q = v1 + s * r + // s = dot(q - v1, r) / dot(r, r) + b2Vec2 r = v2 - v1; + float32 rr = b2Dot(r, r); + if (rr == 0.0f) + { + return false; + } - float32 s = b2Dot(q - v1, r) / rr; - if (s < 0.0f || 1.0f < s) - { - return false; - } + float32 s = b2Dot(q - v1, r) / rr; + if (s < 0.0f || 1.0f < s) + { + return false; + } - output->fraction = t; - if (numerator > 0.0f) - { - output->normal = -normal; - } - else - { - output->normal = normal; - } - return true; + output->fraction = t; + if (numerator > 0.0f) + { + output->normal = -b2Mul(xf.q, normal); + } + else + { + output->normal = b2Mul(xf.q, normal); + } + return true; } void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - b2Vec2 v1 = b2Mul(xf, m_vertex1); - b2Vec2 v2 = b2Mul(xf, m_vertex2); + b2Vec2 v1 = b2Mul(xf, m_vertex1); + b2Vec2 v2 = b2Mul(xf, m_vertex2); - b2Vec2 lower = b2Min(v1, v2); - b2Vec2 upper = b2Max(v1, v2); + b2Vec2 lower = b2Min(v1, v2); + b2Vec2 upper = b2Max(v1, v2); - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; } void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const { - B2_NOT_USED(density); + B2_NOT_USED(density); - massData->mass = 0.0f; - massData->center = 0.5f * (m_vertex1 + m_vertex2); - massData->I = 0.0f; + massData->mass = 0.0f; + massData->center = 0.5f * (m_vertex1 + m_vertex2); + massData->I = 0.0f; } diff --git a/external/Box2D/Collision/Shapes/b2EdgeShape.h b/external/Box2D/Collision/Shapes/b2EdgeShape.h index 6163bcbf1c..0acef8518e 100644 --- a/external/Box2D/Collision/Shapes/b2EdgeShape.h +++ b/external/Box2D/Collision/Shapes/b2EdgeShape.h @@ -27,48 +27,48 @@ class b2EdgeShape : public b2Shape { public: - b2EdgeShape(); + b2EdgeShape(); - /// Set this as an isolated edge. - void Set(const b2Vec2& v1, const b2Vec2& v2); + /// Set this as an isolated edge. + void Set(const b2Vec2& v1, const b2Vec2& v2); - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; - - /// These are the edge vertices - b2Vec2 m_vertex1, m_vertex2; + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; + + /// These are the edge vertices + b2Vec2 m_vertex1, m_vertex2; - /// Optional adjacent vertices. These are used for smooth collision. - b2Vec2 m_vertex0, m_vertex3; - bool m_hasVertex0, m_hasVertex3; + /// Optional adjacent vertices. These are used for smooth collision. + b2Vec2 m_vertex0, m_vertex3; + bool m_hasVertex0, m_hasVertex3; }; inline b2EdgeShape::b2EdgeShape() { - m_type = e_edge; - m_radius = b2_polygonRadius; - m_vertex0.x = 0.0f; - m_vertex0.y = 0.0f; - m_vertex3.x = 0.0f; - m_vertex3.y = 0.0f; - m_hasVertex0 = false; - m_hasVertex3 = false; + m_type = e_edge; + m_radius = b2_polygonRadius; + m_vertex0.x = 0.0f; + m_vertex0.y = 0.0f; + m_vertex3.x = 0.0f; + m_vertex3.y = 0.0f; + m_hasVertex0 = false; + m_hasVertex3 = false; } #endif diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.cpp b/external/Box2D/Collision/Shapes/b2PolygonShape.cpp index c04c1dc49b..2f32e9fe28 100644 --- a/external/Box2D/Collision/Shapes/b2PolygonShape.cpp +++ b/external/Box2D/Collision/Shapes/b2PolygonShape.cpp @@ -21,341 +21,439 @@ b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const { - void* mem = allocator->Allocate(sizeof(b2PolygonShape)); - b2PolygonShape* clone = new (mem) b2PolygonShape; - *clone = *this; - return clone; + void* mem = allocator->Allocate(sizeof(b2PolygonShape)); + b2PolygonShape* clone = new (mem) b2PolygonShape; + *clone = *this; + return clone; } void b2PolygonShape::SetAsBox(float32 hx, float32 hy) { - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid.SetZero(); + m_count = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid.SetZero(); } void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) { - m_vertexCount = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid = center; + m_count = 4; + m_vertices[0].Set(-hx, -hy); + m_vertices[1].Set( hx, -hy); + m_vertices[2].Set( hx, hy); + m_vertices[3].Set(-hx, hy); + m_normals[0].Set(0.0f, -1.0f); + m_normals[1].Set(1.0f, 0.0f); + m_normals[2].Set(0.0f, 1.0f); + m_normals[3].Set(-1.0f, 0.0f); + m_centroid = center; - b2Transform xf; - xf.p = center; - xf.q.Set(angle); + b2Transform xf; + xf.p = center; + xf.q.Set(angle); - // Transform vertices and normals. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = b2Mul(xf, m_vertices[i]); - m_normals[i] = b2Mul(xf.q, m_normals[i]); - } + // Transform vertices and normals. + for (int32 i = 0; i < m_count; ++i) + { + m_vertices[i] = b2Mul(xf, m_vertices[i]); + m_normals[i] = b2Mul(xf.q, m_normals[i]); + } } int32 b2PolygonShape::GetChildCount() const { - return 1; + return 1; } static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) { - b2Assert(count >= 3); + b2Assert(count >= 3); - b2Vec2 c; c.Set(0.0f, 0.0f); - float32 area = 0.0f; + b2Vec2 c; c.Set(0.0f, 0.0f); + float32 area = 0.0f; - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); + // pRef is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 pRef(0.0f, 0.0f); #if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < count; ++i) - { - pRef += vs[i]; - } - pRef *= 1.0f / count; + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < count; ++i) + { + pRef += vs[i]; + } + pRef *= 1.0f / count; #endif - const float32 inv3 = 1.0f / 3.0f; + const float32 inv3 = 1.0f / 3.0f; - for (int32 i = 0; i < count; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = vs[i]; - b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; + for (int32 i = 0; i < count; ++i) + { + // Triangle vertices. + b2Vec2 p1 = pRef; + b2Vec2 p2 = vs[i]; + b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; + b2Vec2 e1 = p2 - p1; + b2Vec2 e2 = p3 - p1; - float32 D = b2Cross(e1, e2); + float32 D = b2Cross(e1, e2); - float32 triangleArea = 0.5f * D; - area += triangleArea; + float32 triangleArea = 0.5f * D; + area += triangleArea; - // Area weighted centroid - c += triangleArea * inv3 * (p1 + p2 + p3); - } + // Area weighted centroid + c += triangleArea * inv3 * (p1 + p2 + p3); + } - // Centroid - b2Assert(area > b2_epsilon); - c *= 1.0f / area; - return c; + // Centroid + b2Assert(area > b2_epsilon); + c *= 1.0f / area; + return c; } void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) { - b2Assert(3 <= count && count <= b2_maxPolygonVertices); - m_vertexCount = count; + b2Assert(3 <= count && count <= b2_maxPolygonVertices); + if (count < 3) + { + SetAsBox(1.0f, 1.0f); + return; + } + + int32 n = b2Min(count, b2_maxPolygonVertices); - // Copy vertices. - for (int32 i = 0; i < m_vertexCount; ++i) - { - m_vertices[i] = vertices[i]; - } + // Perform welding and copy vertices into local buffer. + b2Vec2 ps[b2_maxPolygonVertices]; + int32 tempCount = 0; + for (int32 i = 0; i < n; ++i) + { + b2Vec2 v = vertices[i]; - // Compute normals. Ensure the edges have non-zero length. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); - m_normals[i] = b2Cross(edge, 1.0f); - m_normals[i].Normalize(); - } + bool unique = true; + for (int32 j = 0; j < tempCount; ++j) + { + if (b2DistanceSquared(v, ps[j]) < 0.5f * b2_linearSlop) + { + unique = false; + break; + } + } -#ifdef _DEBUG - // Ensure the polygon is convex and the interior - // is to the left of each edge. - for (int32 i = 0; i < m_vertexCount; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + if (unique) + { + ps[tempCount++] = v; + } + } - for (int32 j = 0; j < m_vertexCount; ++j) - { - // Don't check vertices on the current edge. - if (j == i1 || j == i2) - { - continue; - } - - b2Vec2 r = m_vertices[j] - m_vertices[i1]; + n = tempCount; + if (n < 3) + { + // Polygon is degenerate. + b2Assert(false); + SetAsBox(1.0f, 1.0f); + return; + } - // If this crashes, your polygon is non-convex, has colinear edges, - // or the winding order is wrong. - float32 s = b2Cross(edge, r); - b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); - } - } -#endif + // Create the convex hull using the Gift wrapping algorithm + // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm - // Compute the polygon centroid. - m_centroid = ComputeCentroid(m_vertices, m_vertexCount); + // Find the right most point on the hull + int32 i0 = 0; + float32 x0 = ps[0].x; + for (int32 i = 1; i < n; ++i) + { + float32 x = ps[i].x; + if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) + { + i0 = i; + x0 = x; + } + } + + int32 hull[b2_maxPolygonVertices]; + int32 m = 0; + int32 ih = i0; + + for (;;) + { + hull[m] = ih; + + int32 ie = 0; + for (int32 j = 1; j < n; ++j) + { + if (ie == ih) + { + ie = j; + continue; + } + + b2Vec2 r = ps[ie] - ps[hull[m]]; + b2Vec2 v = ps[j] - ps[hull[m]]; + float32 c = b2Cross(r, v); + if (c < 0.0f) + { + ie = j; + } + + // Collinearity check + if (c == 0.0f && v.LengthSquared() > r.LengthSquared()) + { + ie = j; + } + } + + ++m; + ih = ie; + + if (ie == i0) + { + break; + } + } + + m_count = m; + + // Copy vertices. + for (int32 i = 0; i < m; ++i) + { + m_vertices[i] = ps[hull[i]]; + } + + // Compute normals. Ensure the edges have non-zero length. + for (int32 i = 0; i < m; ++i) + { + int32 i1 = i; + int32 i2 = i + 1 < m ? i + 1 : 0; + b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; + b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); + m_normals[i] = b2Cross(edge, 1.0f); + m_normals[i].Normalize(); + } + + // Compute the polygon centroid. + m_centroid = ComputeCentroid(m_vertices, m); } bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { - b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); + b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); - for (int32 i = 0; i < m_vertexCount; ++i) - { - float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); - if (dot > 0.0f) - { - return false; - } - } + for (int32 i = 0; i < m_count; ++i) + { + float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); + if (dot > 0.0f) + { + return false; + } + } - return true; + return true; } bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const + const b2Transform& xf, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - // Put the ray into the polygon's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; + // Put the ray into the polygon's frame of reference. + b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); + b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); + b2Vec2 d = p2 - p1; - float32 lower = 0.0f, upper = input.maxFraction; + float32 lower = 0.0f, upper = input.maxFraction; - int32 index = -1; + int32 index = -1; - for (int32 i = 0; i < m_vertexCount; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); + for (int32 i = 0; i < m_count; ++i) + { + // p = p1 + a * d + // dot(normal, p - v) = 0 + // dot(normal, p1 - v) + a * dot(normal, d) = 0 + float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); + float32 denominator = b2Dot(m_normals[i], d); - if (denominator == 0.0f) - { - if (numerator < 0.0f) - { - return false; - } - } - else - { - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - } + if (denominator == 0.0f) + { + if (numerator < 0.0f) + { + return false; + } + } + else + { + // Note: we want this predicate without division: + // lower < numerator / denominator, where denominator < 0 + // Since denominator < 0, we have to flip the inequality: + // lower < numerator / denominator <==> denominator * lower > numerator. + if (denominator < 0.0f && numerator < lower * denominator) + { + // Increase lower. + // The segment enters this half-space. + lower = numerator / denominator; + index = i; + } + else if (denominator > 0.0f && numerator < upper * denominator) + { + // Decrease upper. + // The segment exits this half-space. + upper = numerator / denominator; + } + } - // The use of epsilon here causes the assert on lower to trip - // in some cases. Apparently the use of epsilon was to make edge - // shapes work, but now those are handled separately. - //if (upper < lower - b2_epsilon) - if (upper < lower) - { - return false; - } - } + // The use of epsilon here causes the assert on lower to trip + // in some cases. Apparently the use of epsilon was to make edge + // shapes work, but now those are handled separately. + //if (upper < lower - b2_epsilon) + if (upper < lower) + { + return false; + } + } - b2Assert(0.0f <= lower && lower <= input.maxFraction); + b2Assert(0.0f <= lower && lower <= input.maxFraction); - if (index >= 0) - { - output->fraction = lower; - output->normal = b2Mul(xf.q, m_normals[index]); - return true; - } + if (index >= 0) + { + output->fraction = lower; + output->normal = b2Mul(xf.q, m_normals[index]); + return true; + } - return false; + return false; } void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { - B2_NOT_USED(childIndex); + B2_NOT_USED(childIndex); - b2Vec2 lower = b2Mul(xf, m_vertices[0]); - b2Vec2 upper = lower; + b2Vec2 lower = b2Mul(xf, m_vertices[0]); + b2Vec2 upper = lower; - for (int32 i = 1; i < m_vertexCount; ++i) - { - b2Vec2 v = b2Mul(xf, m_vertices[i]); - lower = b2Min(lower, v); - upper = b2Max(upper, v); - } + for (int32 i = 1; i < m_count; ++i) + { + b2Vec2 v = b2Mul(xf, m_vertices[i]); + lower = b2Min(lower, v); + upper = b2Max(upper, v); + } - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; + b2Vec2 r(m_radius, m_radius); + aabb->lowerBound = lower - r; + aabb->upperBound = upper + r; } void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const { - // Polygon mass, centroid, and inertia. - // Let rho be the polygon density in mass per unit area. - // Then: - // mass = rho * int(dA) - // centroid.x = (1/mass) * rho * int(x * dA) - // centroid.y = (1/mass) * rho * int(y * dA) - // I = rho * int((x*x + y*y) * dA) - // - // We can compute these integrals by summing all the integrals - // for each triangle of the polygon. To evaluate the integral - // for a single triangle, we make a change of variables to - // the (u,v) coordinates of the triangle: - // x = x0 + e1x * u + e2x * v - // y = y0 + e1y * u + e2y * v - // where 0 <= u && 0 <= v && u + v <= 1. - // - // We integrate u from [0,1-v] and then v from [0,1]. - // We also need to use the Jacobian of the transformation: - // D = cross(e1, e2) - // - // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) - // - // The rest of the derivation is handled by computer algebra. + // Polygon mass, centroid, and inertia. + // Let rho be the polygon density in mass per unit area. + // Then: + // mass = rho * int(dA) + // centroid.x = (1/mass) * rho * int(x * dA) + // centroid.y = (1/mass) * rho * int(y * dA) + // I = rho * int((x*x + y*y) * dA) + // + // We can compute these integrals by summing all the integrals + // for each triangle of the polygon. To evaluate the integral + // for a single triangle, we make a change of variables to + // the (u,v) coordinates of the triangle: + // x = x0 + e1x * u + e2x * v + // y = y0 + e1y * u + e2y * v + // where 0 <= u && 0 <= v && u + v <= 1. + // + // We integrate u from [0,1-v] and then v from [0,1]. + // We also need to use the Jacobian of the transformation: + // D = cross(e1, e2) + // + // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) + // + // The rest of the derivation is handled by computer algebra. - b2Assert(m_vertexCount >= 3); + b2Assert(m_count >= 3); - b2Vec2 center; center.Set(0.0f, 0.0f); - float32 area = 0.0f; - float32 I = 0.0f; + b2Vec2 center; center.Set(0.0f, 0.0f); + float32 area = 0.0f; + float32 I = 0.0f; - // s is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 s(0.0f, 0.0f); + // s is the reference point for forming triangles. + // It's location doesn't change the result (except for rounding error). + b2Vec2 s(0.0f, 0.0f); - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < m_vertexCount; ++i) - { - s += m_vertices[i]; - } - s *= 1.0f / m_vertexCount; + // This code would put the reference point inside the polygon. + for (int32 i = 0; i < m_count; ++i) + { + s += m_vertices[i]; + } + s *= 1.0f / m_count; - const float32 k_inv3 = 1.0f / 3.0f; + const float32 k_inv3 = 1.0f / 3.0f; - for (int32 i = 0; i < m_vertexCount; ++i) - { - // Triangle vertices. - b2Vec2 e1 = m_vertices[i] - s; - b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s; + for (int32 i = 0; i < m_count; ++i) + { + // Triangle vertices. + b2Vec2 e1 = m_vertices[i] - s; + b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s; - float32 D = b2Cross(e1, e2); + float32 D = b2Cross(e1, e2); - float32 triangleArea = 0.5f * D; - area += triangleArea; + float32 triangleArea = 0.5f * D; + area += triangleArea; - // Area weighted centroid - center += triangleArea * k_inv3 * (e1 + e2); + // Area weighted centroid + center += triangleArea * k_inv3 * (e1 + e2); - float32 ex1 = e1.x, ey1 = e1.y; - float32 ex2 = e2.x, ey2 = e2.y; + float32 ex1 = e1.x, ey1 = e1.y; + float32 ex2 = e2.x, ey2 = e2.y; - float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; - float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; + float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; + float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; - I += (0.25f * k_inv3 * D) * (intx2 + inty2); - } + I += (0.25f * k_inv3 * D) * (intx2 + inty2); + } - // Total mass - massData->mass = density * area; + // Total mass + massData->mass = density * area; - // Center of mass - b2Assert(area > b2_epsilon); - center *= 1.0f / area; - massData->center = center + s; + // Center of mass + b2Assert(area > b2_epsilon); + center *= 1.0f / area; + massData->center = center + s; - // Inertia tensor relative to the local origin (point s). - massData->I = density * I; - - // Shift to center of mass then to original body origin. - massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); + // Inertia tensor relative to the local origin (point s). + massData->I = density * I; + + // Shift to center of mass then to original body origin. + massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); +} + +bool b2PolygonShape::Validate() const +{ + for (int32 i = 0; i < m_count; ++i) + { + int32 i1 = i; + int32 i2 = i < m_count - 1 ? i1 + 1 : 0; + b2Vec2 p = m_vertices[i1]; + b2Vec2 e = m_vertices[i2] - p; + + for (int32 j = 0; j < m_count; ++j) + { + if (j == i1 || j == i2) + { + continue; + } + + b2Vec2 v = m_vertices[j] - p; + float32 c = b2Cross(e, v); + if (c < 0.0f) + { + return false; + } + } + } + + return true; } diff --git a/external/Box2D/Collision/Shapes/b2PolygonShape.h b/external/Box2D/Collision/Shapes/b2PolygonShape.h index 70daccb2ff..b19298038e 100644 --- a/external/Box2D/Collision/Shapes/b2PolygonShape.h +++ b/external/Box2D/Collision/Shapes/b2PolygonShape.h @@ -28,68 +28,74 @@ class b2PolygonShape : public b2Shape { public: - b2PolygonShape(); + b2PolygonShape(); - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const; + /// Implement b2Shape. + b2Shape* Clone(b2BlockAllocator* allocator) const; - /// @see b2Shape::GetChildCount - int32 GetChildCount() const; + /// @see b2Shape::GetChildCount + int32 GetChildCount() const; - /// Copy vertices. This assumes the vertices define a convex polygon. - /// It is assumed that the exterior is the the right of each edge. - /// The count must be in the range [3, b2_maxPolygonVertices]. - void Set(const b2Vec2* vertices, int32 vertexCount); + /// Create a convex hull from the given array of local points. + /// The count must be in the range [3, b2_maxPolygonVertices]. + /// @warning the points may be re-ordered, even if they form a convex polygon + /// @warning collinear points are handled but not removed. Collinear points + /// may lead to poor stacking behavior. + void Set(const b2Vec2* points, int32 count); - /// Build vertices to represent an axis-aligned box. - /// @param hx the half-width. - /// @param hy the half-height. - void SetAsBox(float32 hx, float32 hy); + /// Build vertices to represent an axis-aligned box centered on the local origin. + /// @param hx the half-width. + /// @param hy the half-height. + void SetAsBox(float32 hx, float32 hy); - /// Build vertices to represent an oriented box. - /// @param hx the half-width. - /// @param hy the half-height. - /// @param center the center of the box in local coordinates. - /// @param angle the rotation of the box in local coordinates. - void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); + /// Build vertices to represent an oriented box. + /// @param hx the half-width. + /// @param hy the half-height. + /// @param center the center of the box in local coordinates. + /// @param angle the rotation of the box in local coordinates. + void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; + /// @see b2Shape::TestPoint + bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const; + /// Implement b2Shape. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; + /// @see b2Shape::ComputeAABB + void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const; + /// @see b2Shape::ComputeMass + void ComputeMass(b2MassData* massData, float32 density) const; - /// Get the vertex count. - int32 GetVertexCount() const { return m_vertexCount; } + /// Get the vertex count. + int32 GetVertexCount() const { return m_count; } - /// Get a vertex by index. - const b2Vec2& GetVertex(int32 index) const; + /// Get a vertex by index. + const b2Vec2& GetVertex(int32 index) const; - b2Vec2 m_centroid; - b2Vec2 m_vertices[b2_maxPolygonVertices]; - b2Vec2 m_normals[b2_maxPolygonVertices]; - int32 m_vertexCount; + /// Validate convexity. This is a very time consuming operation. + /// @returns true if valid + bool Validate() const; + + b2Vec2 m_centroid; + b2Vec2 m_vertices[b2_maxPolygonVertices]; + b2Vec2 m_normals[b2_maxPolygonVertices]; + int32 m_count; }; inline b2PolygonShape::b2PolygonShape() { - m_type = e_polygon; - m_radius = b2_polygonRadius; - m_vertexCount = 0; - m_centroid.SetZero(); + m_type = e_polygon; + m_radius = b2_polygonRadius; + m_count = 0; + m_centroid.SetZero(); } inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const { - b2Assert(0 <= index && index < m_vertexCount); - return m_vertices[index]; + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; } #endif diff --git a/external/Box2D/Collision/Shapes/b2Shape.h b/external/Box2D/Collision/Shapes/b2Shape.h index 2e2aedd14a..170ea1a13e 100644 --- a/external/Box2D/Collision/Shapes/b2Shape.h +++ b/external/Box2D/Collision/Shapes/b2Shape.h @@ -26,14 +26,14 @@ /// This holds the mass data computed for a shape. struct b2MassData { - /// The mass of the shape, usually in kilograms. - float32 mass; + /// The mass of the shape, usually in kilograms. + float32 mass; - /// The position of the shape's centroid relative to the shape's origin. - b2Vec2 center; + /// The position of the shape's centroid relative to the shape's origin. + b2Vec2 center; - /// The rotational inertia of the shape about the local origin. - float32 I; + /// The rotational inertia of the shape about the local origin. + float32 I; }; /// A shape is used for collision detection. You can create a shape however you like. @@ -42,60 +42,60 @@ struct b2MassData class b2Shape { public: - - enum Type - { - e_circle = 0, - e_edge = 1, - e_polygon = 2, - e_chain = 3, - e_typeCount = 4 - }; + + enum Type + { + e_circle = 0, + e_edge = 1, + e_polygon = 2, + e_chain = 3, + e_typeCount = 4 + }; - virtual ~b2Shape() {} + virtual ~b2Shape() {} - /// Clone the concrete shape using the provided allocator. - virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; + /// Clone the concrete shape using the provided allocator. + virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; - /// Get the type of this shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - Type GetType() const; + /// Get the type of this shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + Type GetType() const; - /// Get the number of child primitives. - virtual int32 GetChildCount() const = 0; + /// Get the number of child primitives. + virtual int32 GetChildCount() const = 0; - /// Test a point for containment in this shape. This only works for convex shapes. - /// @param xf the shape world transform. - /// @param p a point in world coordinates. - virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; + /// Test a point for containment in this shape. This only works for convex shapes. + /// @param xf the shape world transform. + /// @param p a point in world coordinates. + virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; - /// Cast a ray against a child shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - /// @param transform the transform to be applied to the shape. - /// @param childIndex the child shape index - virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const = 0; + /// Cast a ray against a child shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + /// @param transform the transform to be applied to the shape. + /// @param childIndex the child shape index + virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, + const b2Transform& transform, int32 childIndex) const = 0; - /// Given a transform, compute the associated axis aligned bounding box for a child shape. - /// @param aabb returns the axis aligned box. - /// @param xf the world transform of the shape. - /// @param childIndex the child shape - virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; + /// Given a transform, compute the associated axis aligned bounding box for a child shape. + /// @param aabb returns the axis aligned box. + /// @param xf the world transform of the shape. + /// @param childIndex the child shape + virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; - /// Compute the mass properties of this shape using its dimensions and density. - /// The inertia tensor is computed about the local origin. - /// @param massData returns the mass data for this shape. - /// @param density the density in kilograms per meter squared. - virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; + /// Compute the mass properties of this shape using its dimensions and density. + /// The inertia tensor is computed about the local origin. + /// @param massData returns the mass data for this shape. + /// @param density the density in kilograms per meter squared. + virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; - Type m_type; - float32 m_radius; + Type m_type; + float32 m_radius; }; inline b2Shape::Type b2Shape::GetType() const { - return m_type; + return m_type; } #endif diff --git a/external/Box2D/Collision/b2BroadPhase.cpp b/external/Box2D/Collision/b2BroadPhase.cpp index 431f6de1ee..04e955d235 100644 --- a/external/Box2D/Collision/b2BroadPhase.cpp +++ b/external/Box2D/Collision/b2BroadPhase.cpp @@ -17,106 +17,103 @@ */ #include -#include -using namespace std; b2BroadPhase::b2BroadPhase() { - m_proxyCount = 0; + m_proxyCount = 0; - m_pairCapacity = 16; - m_pairCount = 0; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + m_pairCapacity = 16; + m_pairCount = 0; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - m_moveCapacity = 16; - m_moveCount = 0; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); + m_moveCapacity = 16; + m_moveCount = 0; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); } b2BroadPhase::~b2BroadPhase() { - b2Free(m_moveBuffer); - b2Free(m_pairBuffer); + b2Free(m_moveBuffer); + b2Free(m_pairBuffer); } int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) { - int32 proxyId = m_tree.CreateProxy(aabb, userData); - ++m_proxyCount; - BufferMove(proxyId); - return proxyId; + int32 proxyId = m_tree.CreateProxy(aabb, userData); + ++m_proxyCount; + BufferMove(proxyId); + return proxyId; } void b2BroadPhase::DestroyProxy(int32 proxyId) { - UnBufferMove(proxyId); - --m_proxyCount; - m_tree.DestroyProxy(proxyId); + UnBufferMove(proxyId); + --m_proxyCount; + m_tree.DestroyProxy(proxyId); } void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) { - bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); - if (buffer) - { - BufferMove(proxyId); - } + bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); + if (buffer) + { + BufferMove(proxyId); + } } void b2BroadPhase::TouchProxy(int32 proxyId) { - BufferMove(proxyId); + BufferMove(proxyId); } void b2BroadPhase::BufferMove(int32 proxyId) { - if (m_moveCount == m_moveCapacity) - { - int32* oldBuffer = m_moveBuffer; - m_moveCapacity *= 2; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); - memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); - b2Free(oldBuffer); - } + if (m_moveCount == m_moveCapacity) + { + int32* oldBuffer = m_moveBuffer; + m_moveCapacity *= 2; + m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); + memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); + b2Free(oldBuffer); + } - m_moveBuffer[m_moveCount] = proxyId; - ++m_moveCount; + m_moveBuffer[m_moveCount] = proxyId; + ++m_moveCount; } void b2BroadPhase::UnBufferMove(int32 proxyId) { - for (int32 i = 0; i < m_moveCount; ++i) - { - if (m_moveBuffer[i] == proxyId) - { - m_moveBuffer[i] = e_nullProxy; - return; - } - } + for (int32 i = 0; i < m_moveCount; ++i) + { + if (m_moveBuffer[i] == proxyId) + { + m_moveBuffer[i] = e_nullProxy; + } + } } // This is called from b2DynamicTree::Query when we are gathering pairs. bool b2BroadPhase::QueryCallback(int32 proxyId) { - // A proxy cannot form a pair with itself. - if (proxyId == m_queryProxyId) - { - return true; - } + // A proxy cannot form a pair with itself. + if (proxyId == m_queryProxyId) + { + return true; + } - // Grow the pair buffer as needed. - if (m_pairCount == m_pairCapacity) - { - b2Pair* oldBuffer = m_pairBuffer; - m_pairCapacity *= 2; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); - b2Free(oldBuffer); - } + // Grow the pair buffer as needed. + if (m_pairCount == m_pairCapacity) + { + b2Pair* oldBuffer = m_pairBuffer; + m_pairCapacity *= 2; + m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); + memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); + b2Free(oldBuffer); + } - m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); - m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); - ++m_pairCount; + m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); + m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); + ++m_pairCount; - return true; + return true; } diff --git a/external/Box2D/Collision/b2BroadPhase.h b/external/Box2D/Collision/b2BroadPhase.h index cf2414730a..0c460cabbb 100644 --- a/external/Box2D/Collision/b2BroadPhase.h +++ b/external/Box2D/Collision/b2BroadPhase.h @@ -26,9 +26,8 @@ struct b2Pair { - int32 proxyIdA; - int32 proxyIdB; - int32 next; + int32 proxyIdA; + int32 proxyIdB; }; /// The broad-phase is used for computing pairs and performing volume queries and ray casts. @@ -38,211 +37,221 @@ class b2BroadPhase { public: - enum - { - e_nullProxy = -1 - }; + enum + { + e_nullProxy = -1 + }; - b2BroadPhase(); - ~b2BroadPhase(); + b2BroadPhase(); + ~b2BroadPhase(); - /// Create a proxy with an initial AABB. Pairs are not reported until - /// UpdatePairs is called. - int32 CreateProxy(const b2AABB& aabb, void* userData); + /// Create a proxy with an initial AABB. Pairs are not reported until + /// UpdatePairs is called. + int32 CreateProxy(const b2AABB& aabb, void* userData); - /// Destroy a proxy. It is up to the client to remove any pairs. - void DestroyProxy(int32 proxyId); + /// Destroy a proxy. It is up to the client to remove any pairs. + void DestroyProxy(int32 proxyId); - /// Call MoveProxy as many times as you like, then when you are done - /// call UpdatePairs to finalized the proxy pairs (for your time step). - void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); + /// Call MoveProxy as many times as you like, then when you are done + /// call UpdatePairs to finalized the proxy pairs (for your time step). + void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); - /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. - void TouchProxy(int32 proxyId); + /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. + void TouchProxy(int32 proxyId); - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; - /// Get user data from a proxy. Returns NULL if the id is invalid. - void* GetUserData(int32 proxyId) const; + /// Get user data from a proxy. Returns NULL if the id is invalid. + void* GetUserData(int32 proxyId) const; - /// Test overlap of fat AABBs. - bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; + /// Test overlap of fat AABBs. + bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; - /// Get the number of proxies. - int32 GetProxyCount() const; + /// Get the number of proxies. + int32 GetProxyCount() const; - /// Update the pairs. This results in pair callbacks. This can only add pairs. - template - void UpdatePairs(T* callback); + /// Update the pairs. This results in pair callbacks. This can only add pairs. + template + void UpdatePairs(T* callback); - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; - /// Get the height of the embedded tree. - int32 GetTreeHeight() const; + /// Get the height of the embedded tree. + int32 GetTreeHeight() const; - /// Get the balance of the embedded tree. - int32 GetTreeBalance() const; + /// Get the balance of the embedded tree. + int32 GetTreeBalance() const; - /// Get the quality metric of the embedded tree. - float32 GetTreeQuality() const; + /// Get the quality metric of the embedded tree. + float32 GetTreeQuality() const; + + /// Shift the world origin. Useful for large worlds. + /// The shift formula is: position -= newOrigin + /// @param newOrigin the new origin with respect to the old origin + void ShiftOrigin(const b2Vec2& newOrigin); private: - friend class b2DynamicTree; + friend class b2DynamicTree; - void BufferMove(int32 proxyId); - void UnBufferMove(int32 proxyId); + void BufferMove(int32 proxyId); + void UnBufferMove(int32 proxyId); - bool QueryCallback(int32 proxyId); + bool QueryCallback(int32 proxyId); - b2DynamicTree m_tree; + b2DynamicTree m_tree; - int32 m_proxyCount; + int32 m_proxyCount; - int32* m_moveBuffer; - int32 m_moveCapacity; - int32 m_moveCount; + int32* m_moveBuffer; + int32 m_moveCapacity; + int32 m_moveCount; - b2Pair* m_pairBuffer; - int32 m_pairCapacity; - int32 m_pairCount; + b2Pair* m_pairBuffer; + int32 m_pairCapacity; + int32 m_pairCount; - int32 m_queryProxyId; + int32 m_queryProxyId; }; /// This is used to sort pairs. inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) { - if (pair1.proxyIdA < pair2.proxyIdA) - { - return true; - } + if (pair1.proxyIdA < pair2.proxyIdA) + { + return true; + } - if (pair1.proxyIdA == pair2.proxyIdA) - { - return pair1.proxyIdB < pair2.proxyIdB; - } + if (pair1.proxyIdA == pair2.proxyIdA) + { + return pair1.proxyIdB < pair2.proxyIdB; + } - return false; + return false; } inline void* b2BroadPhase::GetUserData(int32 proxyId) const { - return m_tree.GetUserData(proxyId); + return m_tree.GetUserData(proxyId); } inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const { - const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); - const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); - return b2TestOverlap(aabbA, aabbB); + const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); + const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); + return b2TestOverlap(aabbA, aabbB); } inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const { - return m_tree.GetFatAABB(proxyId); + return m_tree.GetFatAABB(proxyId); } inline int32 b2BroadPhase::GetProxyCount() const { - return m_proxyCount; + return m_proxyCount; } inline int32 b2BroadPhase::GetTreeHeight() const { - return m_tree.GetHeight(); + return m_tree.GetHeight(); } inline int32 b2BroadPhase::GetTreeBalance() const { - return m_tree.GetMaxBalance(); + return m_tree.GetMaxBalance(); } inline float32 b2BroadPhase::GetTreeQuality() const { - return m_tree.GetAreaRatio(); + return m_tree.GetAreaRatio(); } template void b2BroadPhase::UpdatePairs(T* callback) { - // Reset pair buffer - m_pairCount = 0; + // Reset pair buffer + m_pairCount = 0; - // Perform tree queries for all moving proxies. - for (int32 i = 0; i < m_moveCount; ++i) - { - m_queryProxyId = m_moveBuffer[i]; - if (m_queryProxyId == e_nullProxy) - { - continue; - } + // Perform tree queries for all moving proxies. + for (int32 i = 0; i < m_moveCount; ++i) + { + m_queryProxyId = m_moveBuffer[i]; + if (m_queryProxyId == e_nullProxy) + { + continue; + } - // We have to query the tree with the fat AABB so that - // we don't fail to create a pair that may touch later. - const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); + // We have to query the tree with the fat AABB so that + // we don't fail to create a pair that may touch later. + const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); - // Query tree, create pairs and add them pair buffer. - m_tree.Query(this, fatAABB); - } + // Query tree, create pairs and add them pair buffer. + m_tree.Query(this, fatAABB); + } - // Reset move buffer - m_moveCount = 0; + // Reset move buffer + m_moveCount = 0; - // Sort the pair buffer to expose duplicates. - std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); + // Sort the pair buffer to expose duplicates. + std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); - // Send the pairs back to the client. - int32 i = 0; - while (i < m_pairCount) - { - b2Pair* primaryPair = m_pairBuffer + i; - void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); - void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); + // Send the pairs back to the client. + int32 i = 0; + while (i < m_pairCount) + { + b2Pair* primaryPair = m_pairBuffer + i; + void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); + void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); - callback->AddPair(userDataA, userDataB); - ++i; + callback->AddPair(userDataA, userDataB); + ++i; - // Skip any duplicate pairs. - while (i < m_pairCount) - { - b2Pair* pair = m_pairBuffer + i; - if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) - { - break; - } - ++i; - } - } + // Skip any duplicate pairs. + while (i < m_pairCount) + { + b2Pair* pair = m_pairBuffer + i; + if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) + { + break; + } + ++i; + } + } - // Try to keep the tree balanced. - //m_tree.Rebalance(4); + // Try to keep the tree balanced. + //m_tree.Rebalance(4); } template inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const { - m_tree.Query(callback, aabb); + m_tree.Query(callback, aabb); } template inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const { - m_tree.RayCast(callback, input); + m_tree.RayCast(callback, input); +} + +inline void b2BroadPhase::ShiftOrigin(const b2Vec2& newOrigin) +{ + m_tree.ShiftOrigin(newOrigin); } #endif diff --git a/external/Box2D/Collision/b2CollideCircle.cpp b/external/Box2D/Collision/b2CollideCircle.cpp index ed561eb04b..4181fd47cb 100644 --- a/external/Box2D/Collision/b2CollideCircle.cpp +++ b/external/Box2D/Collision/b2CollideCircle.cpp @@ -21,134 +21,134 @@ #include void b2CollideCircles( - b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) + b2Manifold* manifold, + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) { - manifold->pointCount = 0; + manifold->pointCount = 0; - b2Vec2 pA = b2Mul(xfA, circleA->m_p); - b2Vec2 pB = b2Mul(xfB, circleB->m_p); + b2Vec2 pA = b2Mul(xfA, circleA->m_p); + b2Vec2 pB = b2Mul(xfB, circleB->m_p); - b2Vec2 d = pB - pA; - float32 distSqr = b2Dot(d, d); - float32 rA = circleA->m_radius, rB = circleB->m_radius; - float32 radius = rA + rB; - if (distSqr > radius * radius) - { - return; - } + b2Vec2 d = pB - pA; + float32 distSqr = b2Dot(d, d); + float32 rA = circleA->m_radius, rB = circleB->m_radius; + float32 radius = rA + rB; + if (distSqr > radius * radius) + { + return; + } - manifold->type = b2Manifold::e_circles; - manifold->localPoint = circleA->m_p; - manifold->localNormal.SetZero(); - manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localPoint = circleA->m_p; + manifold->localNormal.SetZero(); + manifold->pointCount = 1; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; } void b2CollidePolygonAndCircle( - b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) + b2Manifold* manifold, + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) { - manifold->pointCount = 0; + manifold->pointCount = 0; - // Compute circle position in the frame of the polygon. - b2Vec2 c = b2Mul(xfB, circleB->m_p); - b2Vec2 cLocal = b2MulT(xfA, c); + // Compute circle position in the frame of the polygon. + b2Vec2 c = b2Mul(xfB, circleB->m_p); + b2Vec2 cLocal = b2MulT(xfA, c); - // Find the min separating edge. - int32 normalIndex = 0; - float32 separation = -b2_maxFloat; - float32 radius = polygonA->m_radius + circleB->m_radius; - int32 vertexCount = polygonA->m_vertexCount; - const b2Vec2* vertices = polygonA->m_vertices; - const b2Vec2* normals = polygonA->m_normals; + // Find the min separating edge. + int32 normalIndex = 0; + float32 separation = -b2_maxFloat; + float32 radius = polygonA->m_radius + circleB->m_radius; + int32 vertexCount = polygonA->m_count; + const b2Vec2* vertices = polygonA->m_vertices; + const b2Vec2* normals = polygonA->m_normals; - for (int32 i = 0; i < vertexCount; ++i) - { - float32 s = b2Dot(normals[i], cLocal - vertices[i]); + for (int32 i = 0; i < vertexCount; ++i) + { + float32 s = b2Dot(normals[i], cLocal - vertices[i]); - if (s > radius) - { - // Early out. - return; - } + if (s > radius) + { + // Early out. + return; + } - if (s > separation) - { - separation = s; - normalIndex = i; - } - } + if (s > separation) + { + separation = s; + normalIndex = i; + } + } - // Vertices that subtend the incident face. - int32 vertIndex1 = normalIndex; - int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; - b2Vec2 v1 = vertices[vertIndex1]; - b2Vec2 v2 = vertices[vertIndex2]; + // Vertices that subtend the incident face. + int32 vertIndex1 = normalIndex; + int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; + b2Vec2 v1 = vertices[vertIndex1]; + b2Vec2 v2 = vertices[vertIndex2]; - // If the center is inside the polygon ... - if (separation < b2_epsilon) - { - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[normalIndex]; - manifold->localPoint = 0.5f * (v1 + v2); - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - return; - } + // If the center is inside the polygon ... + if (separation < b2_epsilon) + { + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[normalIndex]; + manifold->localPoint = 0.5f * (v1 + v2); + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + return; + } - // Compute barycentric coordinates - float32 u1 = b2Dot(cLocal - v1, v2 - v1); - float32 u2 = b2Dot(cLocal - v2, v1 - v2); - if (u1 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v1) > radius * radius) - { - return; - } + // Compute barycentric coordinates + float32 u1 = b2Dot(cLocal - v1, v2 - v1); + float32 u2 = b2Dot(cLocal - v2, v1 - v2); + if (u1 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v1) > radius * radius) + { + return; + } - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v1; - manifold->localNormal.Normalize(); - manifold->localPoint = v1; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else if (u2 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v2) > radius * radius) - { - return; - } + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v1; + manifold->localNormal.Normalize(); + manifold->localPoint = v1; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else if (u2 <= 0.0f) + { + if (b2DistanceSquared(cLocal, v2) > radius * radius) + { + return; + } - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v2; - manifold->localNormal.Normalize(); - manifold->localPoint = v2; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else - { - b2Vec2 faceCenter = 0.5f * (v1 + v2); - float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); - if (separation > radius) - { - return; - } + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = cLocal - v2; + manifold->localNormal.Normalize(); + manifold->localPoint = v2; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } + else + { + b2Vec2 faceCenter = 0.5f * (v1 + v2); + float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]); + if (separation > radius) + { + return; + } - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[vertIndex1]; - manifold->localPoint = faceCenter; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = normals[vertIndex1]; + manifold->localPoint = faceCenter; + manifold->points[0].localPoint = circleB->m_p; + manifold->points[0].id.key = 0; + } } diff --git a/external/Box2D/Collision/b2CollideEdge.cpp b/external/Box2D/Collision/b2CollideEdge.cpp index 96ca71dccc..88e311c668 100644 --- a/external/Box2D/Collision/b2CollideEdge.cpp +++ b/external/Box2D/Collision/b2CollideEdge.cpp @@ -25,197 +25,197 @@ // Compute contact points for edge versus circle. // This accounts for edge connectivity. void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB) { - manifold->pointCount = 0; - - // Compute circle in frame of edge - b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); - - b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; - b2Vec2 e = B - A; - - // Barycentric coordinates - float32 u = b2Dot(e, B - Q); - float32 v = b2Dot(e, Q - A); - - float32 radius = edgeA->m_radius + circleB->m_radius; - - b2ContactFeature cf; - cf.indexB = 0; - cf.typeB = b2ContactFeature::e_vertex; - - // Region A - if (v <= 0.0f) - { - b2Vec2 P = A; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to A? - if (edgeA->m_hasVertex0) - { - b2Vec2 A1 = edgeA->m_vertex0; - b2Vec2 B1 = A; - b2Vec2 e1 = B1 - A1; - float32 u1 = b2Dot(e1, B1 - Q); - - // Is the circle in Region AB of the previous edge? - if (u1 > 0.0f) - { - return; - } - } - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region B - if (u <= 0.0f) - { - b2Vec2 P = B; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to B? - if (edgeA->m_hasVertex3) - { - b2Vec2 B2 = edgeA->m_vertex3; - b2Vec2 A2 = B; - b2Vec2 e2 = B2 - A2; - float32 v2 = b2Dot(e2, Q - A2); - - // Is the circle in Region AB of the next edge? - if (v2 > 0.0f) - { - return; - } - } - - cf.indexA = 1; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region AB - float32 den = b2Dot(e, e); - b2Assert(den > 0.0f); - b2Vec2 P = (1.0f / den) * (u * A + v * B); - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - b2Vec2 n(-e.y, e.x); - if (b2Dot(n, Q - A) < 0.0f) - { - n.Set(-n.x, -n.y); - } - n.Normalize(); - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_face; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = n; - manifold->localPoint = A; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; + manifold->pointCount = 0; + + // Compute circle in frame of edge + b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); + + b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; + b2Vec2 e = B - A; + + // Barycentric coordinates + float32 u = b2Dot(e, B - Q); + float32 v = b2Dot(e, Q - A); + + float32 radius = edgeA->m_radius + circleB->m_radius; + + b2ContactFeature cf; + cf.indexB = 0; + cf.typeB = b2ContactFeature::e_vertex; + + // Region A + if (v <= 0.0f) + { + b2Vec2 P = A; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to A? + if (edgeA->m_hasVertex0) + { + b2Vec2 A1 = edgeA->m_vertex0; + b2Vec2 B1 = A; + b2Vec2 e1 = B1 - A1; + float32 u1 = b2Dot(e1, B1 - Q); + + // Is the circle in Region AB of the previous edge? + if (u1 > 0.0f) + { + return; + } + } + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region B + if (u <= 0.0f) + { + b2Vec2 P = B; + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + // Is there an edge connected to B? + if (edgeA->m_hasVertex3) + { + b2Vec2 B2 = edgeA->m_vertex3; + b2Vec2 A2 = B; + b2Vec2 e2 = B2 - A2; + float32 v2 = b2Dot(e2, Q - A2); + + // Is the circle in Region AB of the next edge? + if (v2 > 0.0f) + { + return; + } + } + + cf.indexA = 1; + cf.typeA = b2ContactFeature::e_vertex; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_circles; + manifold->localNormal.SetZero(); + manifold->localPoint = P; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; + return; + } + + // Region AB + float32 den = b2Dot(e, e); + b2Assert(den > 0.0f); + b2Vec2 P = (1.0f / den) * (u * A + v * B); + b2Vec2 d = Q - P; + float32 dd = b2Dot(d, d); + if (dd > radius * radius) + { + return; + } + + b2Vec2 n(-e.y, e.x); + if (b2Dot(n, Q - A) < 0.0f) + { + n.Set(-n.x, -n.y); + } + n.Normalize(); + + cf.indexA = 0; + cf.typeA = b2ContactFeature::e_face; + manifold->pointCount = 1; + manifold->type = b2Manifold::e_faceA; + manifold->localNormal = n; + manifold->localPoint = A; + manifold->points[0].id.key = 0; + manifold->points[0].id.cf = cf; + manifold->points[0].localPoint = circleB->m_p; } // This structure is used to keep track of the best separating axis. struct b2EPAxis { - enum Type - { - e_unknown, - e_edgeA, - e_edgeB - }; - - Type type; - int32 index; - float32 separation; + enum Type + { + e_unknown, + e_edgeA, + e_edgeB + }; + + Type type; + int32 index; + float32 separation; }; // This holds polygon B expressed in frame A. struct b2TempPolygon { - b2Vec2 vertices[b2_maxPolygonVertices]; - b2Vec2 normals[b2_maxPolygonVertices]; - int32 count; + b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 normals[b2_maxPolygonVertices]; + int32 count; }; // Reference face used for clipping struct b2ReferenceFace { - int32 i1, i2; - - b2Vec2 v1, v2; - - b2Vec2 normal; - - b2Vec2 sideNormal1; - float32 sideOffset1; - - b2Vec2 sideNormal2; - float32 sideOffset2; + int32 i1, i2; + + b2Vec2 v1, v2; + + b2Vec2 normal; + + b2Vec2 sideNormal1; + float32 sideOffset1; + + b2Vec2 sideNormal2; + float32 sideOffset2; }; // This class collides and edge and a polygon, taking into account edge adjacency. struct b2EPCollider { - void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - b2EPAxis ComputeEdgeSeparation(); - b2EPAxis ComputePolygonSeparation(); - - enum VertexType - { - e_isolated, - e_concave, - e_convex - }; - - b2TempPolygon m_polygonB; - - b2Transform m_xf; - b2Vec2 m_centroidB; - b2Vec2 m_v0, m_v1, m_v2, m_v3; - b2Vec2 m_normal0, m_normal1, m_normal2; - b2Vec2 m_normal; - VertexType m_type1, m_type2; - b2Vec2 m_lowerLimit, m_upperLimit; - float32 m_radius; - bool m_front; + void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); + b2EPAxis ComputeEdgeSeparation(); + b2EPAxis ComputePolygonSeparation(); + + enum VertexType + { + e_isolated, + e_concave, + e_convex + }; + + b2TempPolygon m_polygonB; + + b2Transform m_xf; + b2Vec2 m_centroidB; + b2Vec2 m_v0, m_v1, m_v2, m_v3; + b2Vec2 m_normal0, m_normal1, m_normal2; + b2Vec2 m_normal; + VertexType m_type1, m_type2; + b2Vec2 m_lowerLimit, m_upperLimit; + float32 m_radius; + bool m_front; }; // Algorithm: @@ -228,471 +228,471 @@ struct b2EPCollider // 7. Return if _any_ axis indicates separation // 8. Clip void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) + const b2PolygonShape* polygonB, const b2Transform& xfB) { - m_xf = b2MulT(xfA, xfB); - - m_centroidB = b2Mul(m_xf, polygonB->m_centroid); - - m_v0 = edgeA->m_vertex0; - m_v1 = edgeA->m_vertex1; - m_v2 = edgeA->m_vertex2; - m_v3 = edgeA->m_vertex3; - - bool hasVertex0 = edgeA->m_hasVertex0; - bool hasVertex3F = edgeA->m_hasVertex3; - - b2Vec2 edge1 = m_v2 - m_v1; - edge1.Normalize(); - m_normal1.Set(edge1.y, -edge1.x); - float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); - float32 offset0 = 0.0f, offset2 = 0.0f; - bool convex1 = false, convex2 = false; - - // Is there a preceding edge? - if (hasVertex0) - { - b2Vec2 edge0 = m_v1 - m_v0; - edge0.Normalize(); - m_normal0.Set(edge0.y, -edge0.x); - convex1 = b2Cross(edge0, edge1) >= 0.0f; - offset0 = b2Dot(m_normal0, m_centroidB - m_v0); - } - - // Is there a following edge? - if (hasVertex3F) - { - b2Vec2 edge2 = m_v3 - m_v2; - edge2.Normalize(); - m_normal2.Set(edge2.y, -edge2.x); - convex2 = b2Cross(edge1, edge2) > 0.0f; - offset2 = b2Dot(m_normal2, m_centroidB - m_v2); - } - - // Determine front or back collision. Determine collision normal limits. - if (hasVertex0 && hasVertex3F) - { - if (convex1 && convex2) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - } - else if (convex1) - { - m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal1; - } - } - else if (convex2) - { - m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal0; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex0) - { - if (convex1) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex3F) - { - if (convex2) - { - m_front = offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - } - else - { - m_front = offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = m_normal1; - } - } - } - else - { - m_front = offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - } - - // Get polygonB in frameA - m_polygonB.count = polygonB->m_vertexCount; - for (int32 i = 0; i < polygonB->m_vertexCount; ++i) - { - m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); - m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); - } - - m_radius = 2.0f * b2_polygonRadius; - - manifold->pointCount = 0; - - b2EPAxis edgeAxis = ComputeEdgeSeparation(); - - // If no valid normal can be found than this edge should not collide. - if (edgeAxis.type == b2EPAxis::e_unknown) - { - return; - } - - if (edgeAxis.separation > m_radius) - { - return; - } - - b2EPAxis polygonAxis = ComputePolygonSeparation(); - if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) - { - return; - } - - // Use hysteresis for jitter reduction. - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - b2EPAxis primaryAxis; - if (polygonAxis.type == b2EPAxis::e_unknown) - { - primaryAxis = edgeAxis; - } - else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) - { - primaryAxis = polygonAxis; - } - else - { - primaryAxis = edgeAxis; - } - - b2ClipVertex ie[2]; - b2ReferenceFace rf; - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->type = b2Manifold::e_faceA; - - // Search for the polygon normal that is most anti-parallel to the edge normal. - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); - for (int32 i = 1; i < m_polygonB.count; ++i) - { - float32 value = b2Dot(m_normal, m_polygonB.normals[i]); - if (value < bestValue) - { - bestValue = value; - bestIndex = i; - } - } - - int32 i1 = bestIndex; - int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; - - ie[0].v = m_polygonB.vertices[i1]; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = i1; - ie[0].id.cf.typeA = b2ContactFeature::e_face; - ie[0].id.cf.typeB = b2ContactFeature::e_vertex; - - ie[1].v = m_polygonB.vertices[i2]; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = i2; - ie[1].id.cf.typeA = b2ContactFeature::e_face; - ie[1].id.cf.typeB = b2ContactFeature::e_vertex; - - if (m_front) - { - rf.i1 = 0; - rf.i2 = 1; - rf.v1 = m_v1; - rf.v2 = m_v2; - rf.normal = m_normal1; - } - else - { - rf.i1 = 1; - rf.i2 = 0; - rf.v1 = m_v2; - rf.v2 = m_v1; - rf.normal = -m_normal1; - } - } - else - { - manifold->type = b2Manifold::e_faceB; - - ie[0].v = m_v1; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = primaryAxis.index; - ie[0].id.cf.typeA = b2ContactFeature::e_vertex; - ie[0].id.cf.typeB = b2ContactFeature::e_face; - - ie[1].v = m_v2; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = primaryAxis.index; - ie[1].id.cf.typeA = b2ContactFeature::e_vertex; - ie[1].id.cf.typeB = b2ContactFeature::e_face; - - rf.i1 = primaryAxis.index; - rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; - rf.v1 = m_polygonB.vertices[rf.i1]; - rf.v2 = m_polygonB.vertices[rf.i2]; - rf.normal = m_polygonB.normals[rf.i1]; - } - - rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); - rf.sideNormal2 = -rf.sideNormal1; - rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); - rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int32 np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Now clipPoints2 contains the clipped points. - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->localNormal = rf.normal; - manifold->localPoint = rf.v1; - } - else - { - manifold->localNormal = polygonB->m_normals[rf.i1]; - manifold->localPoint = polygonB->m_vertices[rf.i1]; - } - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation; - - separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); - - if (separation <= m_radius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - } - else - { - cp->localPoint = clipPoints2[i].v; - cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; - cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; - cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; - cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; - } - - ++pointCount; - } - } - - manifold->pointCount = pointCount; + m_xf = b2MulT(xfA, xfB); + + m_centroidB = b2Mul(m_xf, polygonB->m_centroid); + + m_v0 = edgeA->m_vertex0; + m_v1 = edgeA->m_vertex1; + m_v2 = edgeA->m_vertex2; + m_v3 = edgeA->m_vertex3; + + bool hasVertex0 = edgeA->m_hasVertex0; + bool hasVertex3 = edgeA->m_hasVertex3; + + b2Vec2 edge1 = m_v2 - m_v1; + edge1.Normalize(); + m_normal1.Set(edge1.y, -edge1.x); + float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); + float32 offset0 = 0.0f, offset2 = 0.0f; + bool convex1 = false, convex2 = false; + + // Is there a preceding edge? + if (hasVertex0) + { + b2Vec2 edge0 = m_v1 - m_v0; + edge0.Normalize(); + m_normal0.Set(edge0.y, -edge0.x); + convex1 = b2Cross(edge0, edge1) >= 0.0f; + offset0 = b2Dot(m_normal0, m_centroidB - m_v0); + } + + // Is there a following edge? + if (hasVertex3) + { + b2Vec2 edge2 = m_v3 - m_v2; + edge2.Normalize(); + m_normal2.Set(edge2.y, -edge2.x); + convex2 = b2Cross(edge1, edge2) > 0.0f; + offset2 = b2Dot(m_normal2, m_centroidB - m_v2); + } + + // Determine front or back collision. Determine collision normal limits. + if (hasVertex0 && hasVertex3) + { + if (convex1 && convex2) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + } + else if (convex1) + { + m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal1; + } + } + else if (convex2) + { + m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal0; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex0) + { + if (convex1) + { + m_front = offset0 >= 0.0f || offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal0; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + } + else + { + m_front = offset0 >= 0.0f && offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = -m_normal0; + } + } + } + else if (hasVertex3) + { + if (convex2) + { + m_front = offset1 >= 0.0f || offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal2; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + } + else + { + m_front = offset1 >= 0.0f && offset2 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = -m_normal2; + m_upperLimit = m_normal1; + } + } + } + else + { + m_front = offset1 >= 0.0f; + if (m_front) + { + m_normal = m_normal1; + m_lowerLimit = -m_normal1; + m_upperLimit = -m_normal1; + } + else + { + m_normal = -m_normal1; + m_lowerLimit = m_normal1; + m_upperLimit = m_normal1; + } + } + + // Get polygonB in frameA + m_polygonB.count = polygonB->m_count; + for (int32 i = 0; i < polygonB->m_count; ++i) + { + m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); + m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); + } + + m_radius = 2.0f * b2_polygonRadius; + + manifold->pointCount = 0; + + b2EPAxis edgeAxis = ComputeEdgeSeparation(); + + // If no valid normal can be found than this edge should not collide. + if (edgeAxis.type == b2EPAxis::e_unknown) + { + return; + } + + if (edgeAxis.separation > m_radius) + { + return; + } + + b2EPAxis polygonAxis = ComputePolygonSeparation(); + if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) + { + return; + } + + // Use hysteresis for jitter reduction. + const float32 k_relativeTol = 0.98f; + const float32 k_absoluteTol = 0.001f; + + b2EPAxis primaryAxis; + if (polygonAxis.type == b2EPAxis::e_unknown) + { + primaryAxis = edgeAxis; + } + else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) + { + primaryAxis = polygonAxis; + } + else + { + primaryAxis = edgeAxis; + } + + b2ClipVertex ie[2]; + b2ReferenceFace rf; + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->type = b2Manifold::e_faceA; + + // Search for the polygon normal that is most anti-parallel to the edge normal. + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); + for (int32 i = 1; i < m_polygonB.count; ++i) + { + float32 value = b2Dot(m_normal, m_polygonB.normals[i]); + if (value < bestValue) + { + bestValue = value; + bestIndex = i; + } + } + + int32 i1 = bestIndex; + int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; + + ie[0].v = m_polygonB.vertices[i1]; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = static_cast(i1); + ie[0].id.cf.typeA = b2ContactFeature::e_face; + ie[0].id.cf.typeB = b2ContactFeature::e_vertex; + + ie[1].v = m_polygonB.vertices[i2]; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = static_cast(i2); + ie[1].id.cf.typeA = b2ContactFeature::e_face; + ie[1].id.cf.typeB = b2ContactFeature::e_vertex; + + if (m_front) + { + rf.i1 = 0; + rf.i2 = 1; + rf.v1 = m_v1; + rf.v2 = m_v2; + rf.normal = m_normal1; + } + else + { + rf.i1 = 1; + rf.i2 = 0; + rf.v1 = m_v2; + rf.v2 = m_v1; + rf.normal = -m_normal1; + } + } + else + { + manifold->type = b2Manifold::e_faceB; + + ie[0].v = m_v1; + ie[0].id.cf.indexA = 0; + ie[0].id.cf.indexB = static_cast(primaryAxis.index); + ie[0].id.cf.typeA = b2ContactFeature::e_vertex; + ie[0].id.cf.typeB = b2ContactFeature::e_face; + + ie[1].v = m_v2; + ie[1].id.cf.indexA = 0; + ie[1].id.cf.indexB = static_cast(primaryAxis.index); + ie[1].id.cf.typeA = b2ContactFeature::e_vertex; + ie[1].id.cf.typeB = b2ContactFeature::e_face; + + rf.i1 = primaryAxis.index; + rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; + rf.v1 = m_polygonB.vertices[rf.i1]; + rf.v2 = m_polygonB.vertices[rf.i2]; + rf.normal = m_polygonB.normals[rf.i1]; + } + + rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); + rf.sideNormal2 = -rf.sideNormal1; + rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); + rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); + + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int32 np; + + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); + + if (np < b2_maxManifoldPoints) + { + return; + } + + // Now clipPoints2 contains the clipped points. + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + manifold->localNormal = rf.normal; + manifold->localPoint = rf.v1; + } + else + { + manifold->localNormal = polygonB->m_normals[rf.i1]; + manifold->localPoint = polygonB->m_vertices[rf.i1]; + } + + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation; + + separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); + + if (separation <= m_radius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + + if (primaryAxis.type == b2EPAxis::e_edgeA) + { + cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + } + else + { + cp->localPoint = clipPoints2[i].v; + cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; + cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; + cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; + cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; + } + + ++pointCount; + } + } + + manifold->pointCount = pointCount; } b2EPAxis b2EPCollider::ComputeEdgeSeparation() { - b2EPAxis axis; - axis.type = b2EPAxis::e_edgeA; - axis.index = m_front ? 0 : 1; - axis.separation = FLT_MAX; - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); - if (s < axis.separation) - { - axis.separation = s; - } - } - - return axis; + b2EPAxis axis; + axis.type = b2EPAxis::e_edgeA; + axis.index = m_front ? 0 : 1; + axis.separation = FLT_MAX; + + for (int32 i = 0; i < m_polygonB.count; ++i) + { + float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); + if (s < axis.separation) + { + axis.separation = s; + } + } + + return axis; } b2EPAxis b2EPCollider::ComputePolygonSeparation() { - b2EPAxis axis; - axis.type = b2EPAxis::e_unknown; - axis.index = -1; - axis.separation = -FLT_MAX; + b2EPAxis axis; + axis.type = b2EPAxis::e_unknown; + axis.index = -1; + axis.separation = -FLT_MAX; - b2Vec2 perp(-m_normal.y, m_normal.x); + b2Vec2 perp(-m_normal.y, m_normal.x); - for (int32 i = 0; i < m_polygonB.count; ++i) - { - b2Vec2 n = -m_polygonB.normals[i]; - - float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); - float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); - float32 s = b2Min(s1, s2); - - if (s > m_radius) - { - // No collision - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - return axis; - } - - // Adjacency - if (b2Dot(n, perp) >= 0.0f) - { - if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - else - { - if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - - if (s > axis.separation) - { - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - } - } - - return axis; + for (int32 i = 0; i < m_polygonB.count; ++i) + { + b2Vec2 n = -m_polygonB.normals[i]; + + float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); + float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); + float32 s = b2Min(s1, s2); + + if (s > m_radius) + { + // No collision + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + return axis; + } + + // Adjacency + if (b2Dot(n, perp) >= 0.0f) + { + if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + else + { + if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) + { + continue; + } + } + + if (s > axis.separation) + { + axis.type = b2EPAxis::e_edgeB; + axis.index = i; + axis.separation = s; + } + } + + return axis; } -void b2CollideEdgeAndPolygon( b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) +void b2CollideEdgeAndPolygon( b2Manifold* manifold, + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB) { - b2EPCollider collider; - collider.Collide(manifold, edgeA, xfA, polygonB, xfB); + b2EPCollider collider; + collider.Collide(manifold, edgeA, xfA, polygonB, xfB); } diff --git a/external/Box2D/Collision/b2CollidePolygon.cpp b/external/Box2D/Collision/b2CollidePolygon.cpp index be2518d966..0aac38b2ac 100644 --- a/external/Box2D/Collision/b2CollidePolygon.cpp +++ b/external/Box2D/Collision/b2CollidePolygon.cpp @@ -19,168 +19,91 @@ #include #include -// Find the separation between poly1 and poly2 for a give edge normal on poly1. -static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* vertices1 = poly1->m_vertices; - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); - - // Convert normal from poly1's frame into poly2's frame. - b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]); - b2Vec2 normal1 = b2MulT(xf2.q, normal1World); - - // Find support vertex on poly2 for -normal. - int32 index = 0; - float32 minDot = b2_maxFloat; - - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(vertices2[i], normal1); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]); - b2Vec2 v2 = b2Mul(xf2, vertices2[index]); - float32 separation = b2Dot(v2 - v1, normal1World); - return separation; -} - // Find the max separation between poly1 and poly2 using edge normals from poly1. static float32 b2FindMaxSeparation(int32* edgeIndex, - const b2PolygonShape* poly1, const b2Transform& xf1, - const b2PolygonShape* poly2, const b2Transform& xf2) + const b2PolygonShape* poly1, const b2Transform& xf1, + const b2PolygonShape* poly2, const b2Transform& xf2) { - int32 count1 = poly1->m_vertexCount; - const b2Vec2* normals1 = poly1->m_normals; + int32 count1 = poly1->m_count; + int32 count2 = poly2->m_count; + const b2Vec2* n1s = poly1->m_normals; + const b2Vec2* v1s = poly1->m_vertices; + const b2Vec2* v2s = poly2->m_vertices; + b2Transform xf = b2MulT(xf2, xf1); - // Vector pointing from the centroid of poly1 to the centroid of poly2. - b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid); - b2Vec2 dLocal1 = b2MulT(xf1.q, d); + int32 bestIndex = 0; + float32 maxSeparation = -b2_maxFloat; + for (int32 i = 0; i < count1; ++i) + { + // Get poly1 normal in frame2. + b2Vec2 n = b2Mul(xf.q, n1s[i]); + b2Vec2 v1 = b2Mul(xf, v1s[i]); - // Find edge normal on poly1 that has the largest projection onto d. - int32 edge = 0; - float32 maxDot = -b2_maxFloat; - for (int32 i = 0; i < count1; ++i) - { - float32 dot = b2Dot(normals1[i], dLocal1); - if (dot > maxDot) - { - maxDot = dot; - edge = i; - } - } + // Find deepest point for normal i. + float32 si = b2_maxFloat; + for (int32 j = 0; j < count2; ++j) + { + float32 sij = b2Dot(n, v2s[j] - v1); + if (sij < si) + { + si = sij; + } + } - // Get the separation for the edge normal. - float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); + if (si > maxSeparation) + { + maxSeparation = si; + bestIndex = i; + } + } - // Check the separation for the previous edge normal. - int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1; - float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); - - // Check the separation for the next edge normal. - int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0; - float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); - - // Find the best edge and the search direction. - int32 bestEdge; - float32 bestSeparation; - int32 increment; - if (sPrev > s && sPrev > sNext) - { - increment = -1; - bestEdge = prevEdge; - bestSeparation = sPrev; - } - else if (sNext > s) - { - increment = 1; - bestEdge = nextEdge; - bestSeparation = sNext; - } - else - { - *edgeIndex = edge; - return s; - } - - // Perform a local search for the best edge normal. - for ( ; ; ) - { - if (increment == -1) - edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1; - else - edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0; - - s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); - - if (s > bestSeparation) - { - bestEdge = edge; - bestSeparation = s; - } - else - { - break; - } - } - - *edgeIndex = bestEdge; - return bestSeparation; + *edgeIndex = bestIndex; + return maxSeparation; } static void b2FindIncidentEdge(b2ClipVertex c[2], - const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) + const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, + const b2PolygonShape* poly2, const b2Transform& xf2) { - const b2Vec2* normals1 = poly1->m_normals; + const b2Vec2* normals1 = poly1->m_normals; - int32 count2 = poly2->m_vertexCount; - const b2Vec2* vertices2 = poly2->m_vertices; - const b2Vec2* normals2 = poly2->m_normals; + int32 count2 = poly2->m_count; + const b2Vec2* vertices2 = poly2->m_vertices; + const b2Vec2* normals2 = poly2->m_normals; - b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount); + b2Assert(0 <= edge1 && edge1 < poly1->m_count); - // Get the normal of the reference edge in poly2's frame. - b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); + // Get the normal of the reference edge in poly2's frame. + b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); - // Find the incident edge on poly2. - int32 index = 0; - float32 minDot = b2_maxFloat; - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(normal1, normals2[i]); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } + // Find the incident edge on poly2. + int32 index = 0; + float32 minDot = b2_maxFloat; + for (int32 i = 0; i < count2; ++i) + { + float32 dot = b2Dot(normal1, normals2[i]); + if (dot < minDot) + { + minDot = dot; + index = i; + } + } - // Build the clip vertices for the incident edge. - int32 i1 = index; - int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; + // Build the clip vertices for the incident edge. + int32 i1 = index; + int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; - c[0].v = b2Mul(xf2, vertices2[i1]); - c[0].id.cf.indexA = (uint8)edge1; - c[0].id.cf.indexB = (uint8)i1; - c[0].id.cf.typeA = b2ContactFeature::e_face; - c[0].id.cf.typeB = b2ContactFeature::e_vertex; + c[0].v = b2Mul(xf2, vertices2[i1]); + c[0].id.cf.indexA = (uint8)edge1; + c[0].id.cf.indexB = (uint8)i1; + c[0].id.cf.typeA = b2ContactFeature::e_face; + c[0].id.cf.typeB = b2ContactFeature::e_vertex; - c[1].v = b2Mul(xf2, vertices2[i2]); - c[1].id.cf.indexA = (uint8)edge1; - c[1].id.cf.indexB = (uint8)i2; - c[1].id.cf.typeA = b2ContactFeature::e_face; - c[1].id.cf.typeB = b2ContactFeature::e_vertex; + c[1].v = b2Mul(xf2, vertices2[i2]); + c[1].id.cf.indexA = (uint8)edge1; + c[1].id.cf.indexB = (uint8)i2; + c[1].id.cf.typeA = b2ContactFeature::e_face; + c[1].id.cf.typeB = b2ContactFeature::e_vertex; } // Find edge normal of max separation on A - return if separating axis is found @@ -191,127 +114,126 @@ static void b2FindIncidentEdge(b2ClipVertex c[2], // The normal points from 1 to 2 void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polyA, const b2Transform& xfA, - const b2PolygonShape* polyB, const b2Transform& xfB) + const b2PolygonShape* polyA, const b2Transform& xfA, + const b2PolygonShape* polyB, const b2Transform& xfB) { - manifold->pointCount = 0; - float32 totalRadius = polyA->m_radius + polyB->m_radius; + manifold->pointCount = 0; + float32 totalRadius = polyA->m_radius + polyB->m_radius; - int32 edgeA = 0; - float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); - if (separationA > totalRadius) - return; + int32 edgeA = 0; + float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); + if (separationA > totalRadius) + return; - int32 edgeB = 0; - float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); - if (separationB > totalRadius) - return; + int32 edgeB = 0; + float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); + if (separationB > totalRadius) + return; - const b2PolygonShape* poly1; // reference polygon - const b2PolygonShape* poly2; // incident polygon - b2Transform xf1, xf2; - int32 edge1; // reference edge - uint8 flip; - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; + const b2PolygonShape* poly1; // reference polygon + const b2PolygonShape* poly2; // incident polygon + b2Transform xf1, xf2; + int32 edge1; // reference edge + uint8 flip; + const float32 k_tol = 0.1f * b2_linearSlop; - if (separationB > k_relativeTol * separationA + k_absoluteTol) - { - poly1 = polyB; - poly2 = polyA; - xf1 = xfB; - xf2 = xfA; - edge1 = edgeB; - manifold->type = b2Manifold::e_faceB; - flip = 1; - } - else - { - poly1 = polyA; - poly2 = polyB; - xf1 = xfA; - xf2 = xfB; - edge1 = edgeA; - manifold->type = b2Manifold::e_faceA; - flip = 0; - } + if (separationB > separationA + k_tol) + { + poly1 = polyB; + poly2 = polyA; + xf1 = xfB; + xf2 = xfA; + edge1 = edgeB; + manifold->type = b2Manifold::e_faceB; + flip = 1; + } + else + { + poly1 = polyA; + poly2 = polyB; + xf1 = xfA; + xf2 = xfB; + edge1 = edgeA; + manifold->type = b2Manifold::e_faceA; + flip = 0; + } - b2ClipVertex incidentEdge[2]; - b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); + b2ClipVertex incidentEdge[2]; + b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); - int32 count1 = poly1->m_vertexCount; - const b2Vec2* vertices1 = poly1->m_vertices; + int32 count1 = poly1->m_count; + const b2Vec2* vertices1 = poly1->m_vertices; - int32 iv1 = edge1; - int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; + int32 iv1 = edge1; + int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; - b2Vec2 v11 = vertices1[iv1]; - b2Vec2 v12 = vertices1[iv2]; + b2Vec2 v11 = vertices1[iv1]; + b2Vec2 v12 = vertices1[iv2]; - b2Vec2 localTangent = v12 - v11; - localTangent.Normalize(); - - b2Vec2 localNormal = b2Cross(localTangent, 1.0f); - b2Vec2 planePoint = 0.5f * (v11 + v12); + b2Vec2 localTangent = v12 - v11; + localTangent.Normalize(); + + b2Vec2 localNormal = b2Cross(localTangent, 1.0f); + b2Vec2 planePoint = 0.5f * (v11 + v12); - b2Vec2 tangent = b2Mul(xf1.q, localTangent); - b2Vec2 normal = b2Cross(tangent, 1.0f); - - v11 = b2Mul(xf1, v11); - v12 = b2Mul(xf1, v12); + b2Vec2 tangent = b2Mul(xf1.q, localTangent); + b2Vec2 normal = b2Cross(tangent, 1.0f); + + v11 = b2Mul(xf1, v11); + v12 = b2Mul(xf1, v12); - // Face offset. - float32 frontOffset = b2Dot(normal, v11); + // Face offset. + float32 frontOffset = b2Dot(normal, v11); - // Side offsets, extended by polytope skin thickness. - float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; - float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; + // Side offsets, extended by polytope skin thickness. + float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; + float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int np; + // Clip incident edge against extruded edge1 side edges. + b2ClipVertex clipPoints1[2]; + b2ClipVertex clipPoints2[2]; + int np; - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); + // Clip to box side 1 + np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); - if (np < 2) - return; + if (np < 2) + return; - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); + // Clip to negative box side 1 + np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); - if (np < 2) - { - return; - } + if (np < 2) + { + return; + } - // Now clipPoints2 contains the clipped points. - manifold->localNormal = localNormal; - manifold->localPoint = planePoint; + // Now clipPoints2 contains the clipped points. + manifold->localNormal = localNormal; + manifold->localPoint = planePoint; - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; + int32 pointCount = 0; + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; - if (separation <= totalRadius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - cp->localPoint = b2MulT(xf2, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - if (flip) - { - // Swap features - b2ContactFeature cf = cp->id.cf; - cp->id.cf.indexA = cf.indexB; - cp->id.cf.indexB = cf.indexA; - cp->id.cf.typeA = cf.typeB; - cp->id.cf.typeB = cf.typeA; - } - ++pointCount; - } - } + if (separation <= totalRadius) + { + b2ManifoldPoint* cp = manifold->points + pointCount; + cp->localPoint = b2MulT(xf2, clipPoints2[i].v); + cp->id = clipPoints2[i].id; + if (flip) + { + // Swap features + b2ContactFeature cf = cp->id.cf; + cp->id.cf.indexA = cf.indexB; + cp->id.cf.indexB = cf.indexA; + cp->id.cf.typeA = cf.typeB; + cp->id.cf.typeB = cf.typeA; + } + ++pointCount; + } + } - manifold->pointCount = pointCount; + manifold->pointCount = pointCount; } diff --git a/external/Box2D/Collision/b2Collision.cpp b/external/Box2D/Collision/b2Collision.cpp index 2dd5ff0ab6..4ebf35565e 100644 --- a/external/Box2D/Collision/b2Collision.cpp +++ b/external/Box2D/Collision/b2Collision.cpp @@ -20,230 +20,233 @@ #include void b2WorldManifold::Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB) + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB) { - if (manifold->pointCount == 0) - { - return; - } + if (manifold->pointCount == 0) + { + return; + } - switch (manifold->type) - { - case b2Manifold::e_circles: - { - normal.Set(1.0f, 0.0f); - b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); - b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } + switch (manifold->type) + { + case b2Manifold::e_circles: + { + normal.Set(1.0f, 0.0f); + b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); + b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); + if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) + { + normal = pointB - pointA; + normal.Normalize(); + } - b2Vec2 cA = pointA + radiusA * normal; - b2Vec2 cB = pointB - radiusB * normal; - points[0] = 0.5f * (cA + cB); - } - break; + b2Vec2 cA = pointA + radiusA * normal; + b2Vec2 cB = pointB - radiusB * normal; + points[0] = 0.5f * (cA + cB); + separations[0] = b2Dot(cB - cA, normal); + } + break; - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); - b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cB = clipPoint - radiusB * normal; - points[i] = 0.5f * (cA + cB); - } - } - break; + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); + + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); + b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cB = clipPoint - radiusB * normal; + points[i] = 0.5f * (cA + cB); + separations[i] = b2Dot(cB - cA, normal); + } + } + break; - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, manifold->localNormal); + b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); - b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cA = clipPoint - radiusA * normal; - points[i] = 0.5f * (cA + cB); - } + for (int32 i = 0; i < manifold->pointCount; ++i) + { + b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); + b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; + b2Vec2 cA = clipPoint - radiusA * normal; + points[i] = 0.5f * (cA + cB); + separations[i] = b2Dot(cA - cB, normal); + } - // Ensure normal points from A to B. - normal = -normal; - } - break; - } + // Ensure normal points from A to B. + normal = -normal; + } + break; + } } void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2) + const b2Manifold* manifold1, const b2Manifold* manifold2) { - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - state1[i] = b2_nullState; - state2[i] = b2_nullState; - } + for (int32 i = 0; i < b2_maxManifoldPoints; ++i) + { + state1[i] = b2_nullState; + state2[i] = b2_nullState; + } - // Detect persists and removes. - for (int32 i = 0; i < manifold1->pointCount; ++i) - { - b2ContactID id = manifold1->points[i].id; + // Detect persists and removes. + for (int32 i = 0; i < manifold1->pointCount; ++i) + { + b2ContactID id = manifold1->points[i].id; - state1[i] = b2_removeState; + state1[i] = b2_removeState; - for (int32 j = 0; j < manifold2->pointCount; ++j) - { - if (manifold2->points[j].id.key == id.key) - { - state1[i] = b2_persistState; - break; - } - } - } + for (int32 j = 0; j < manifold2->pointCount; ++j) + { + if (manifold2->points[j].id.key == id.key) + { + state1[i] = b2_persistState; + break; + } + } + } - // Detect persists and adds. - for (int32 i = 0; i < manifold2->pointCount; ++i) - { - b2ContactID id = manifold2->points[i].id; + // Detect persists and adds. + for (int32 i = 0; i < manifold2->pointCount; ++i) + { + b2ContactID id = manifold2->points[i].id; - state2[i] = b2_addState; + state2[i] = b2_addState; - for (int32 j = 0; j < manifold1->pointCount; ++j) - { - if (manifold1->points[j].id.key == id.key) - { - state2[i] = b2_persistState; - break; - } - } - } + for (int32 j = 0; j < manifold1->pointCount; ++j) + { + if (manifold1->points[j].id.key == id.key) + { + state2[i] = b2_persistState; + break; + } + } + } } // From Real-time Collision Detection, p179. bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const { - float32 tmin = -b2_maxFloat; - float32 tmax = b2_maxFloat; + float32 tmin = -b2_maxFloat; + float32 tmax = b2_maxFloat; - b2Vec2 p = input.p1; - b2Vec2 d = input.p2 - input.p1; - b2Vec2 absD = b2Abs(d); + b2Vec2 p = input.p1; + b2Vec2 d = input.p2 - input.p1; + b2Vec2 absD = b2Abs(d); - b2Vec2 normal; + b2Vec2 normal; - for (int32 i = 0; i < 2; ++i) - { - if (absD(i) < b2_epsilon) - { - // Parallel. - if (p(i) < lowerBound(i) || upperBound(i) < p(i)) - { - return false; - } - } - else - { - float32 inv_d = 1.0f / d(i); - float32 t1 = (lowerBound(i) - p(i)) * inv_d; - float32 t2 = (upperBound(i) - p(i)) * inv_d; + for (int32 i = 0; i < 2; ++i) + { + if (absD(i) < b2_epsilon) + { + // Parallel. + if (p(i) < lowerBound(i) || upperBound(i) < p(i)) + { + return false; + } + } + else + { + float32 inv_d = 1.0f / d(i); + float32 t1 = (lowerBound(i) - p(i)) * inv_d; + float32 t2 = (upperBound(i) - p(i)) * inv_d; - // Sign of the normal vector. - float32 s = -1.0f; + // Sign of the normal vector. + float32 s = -1.0f; - if (t1 > t2) - { - b2Swap(t1, t2); - s = 1.0f; - } + if (t1 > t2) + { + b2Swap(t1, t2); + s = 1.0f; + } - // Push the min up - if (t1 > tmin) - { - normal.SetZero(); - normal(i) = s; - tmin = t1; - } + // Push the min up + if (t1 > tmin) + { + normal.SetZero(); + normal(i) = s; + tmin = t1; + } - // Pull the max down - tmax = b2Min(tmax, t2); + // Pull the max down + tmax = b2Min(tmax, t2); - if (tmin > tmax) - { - return false; - } - } - } + if (tmin > tmax) + { + return false; + } + } + } - // Does the ray start inside the box? - // Does the ray intersect beyond the max fraction? - if (tmin < 0.0f || input.maxFraction < tmin) - { - return false; - } + // Does the ray start inside the box? + // Does the ray intersect beyond the max fraction? + if (tmin < 0.0f || input.maxFraction < tmin) + { + return false; + } - // Intersection. - output->fraction = tmin; - output->normal = normal; - return true; + // Intersection. + output->fraction = tmin; + output->normal = normal; + return true; } // Sutherland-Hodgman clipping. int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA) + const b2Vec2& normal, float32 offset, int32 vertexIndexA) { - // Start with no output points - int32 numOut = 0; + // Start with no output points + int32 numOut = 0; - // Calculate the distance of end points to the line - float32 distance0 = b2Dot(normal, vIn[0].v) - offset; - float32 distance1 = b2Dot(normal, vIn[1].v) - offset; + // Calculate the distance of end points to the line + float32 distance0 = b2Dot(normal, vIn[0].v) - offset; + float32 distance1 = b2Dot(normal, vIn[1].v) - offset; - // If the points are behind the plane - if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; - if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; + // If the points are behind the plane + if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; + if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; - // If the points are on different sides of the plane - if (distance0 * distance1 < 0.0f) - { - // Find intersection point of edge and plane - float32 interp = distance0 / (distance0 - distance1); - vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); + // If the points are on different sides of the plane + if (distance0 * distance1 < 0.0f) + { + // Find intersection point of edge and plane + float32 interp = distance0 / (distance0 - distance1); + vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - // VertexA is hitting edgeB. - vOut[numOut].id.cf.indexA = vertexIndexA; - vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; - vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; - vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; - ++numOut; - } + // VertexA is hitting edgeB. + vOut[numOut].id.cf.indexA = static_cast(vertexIndexA); + vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; + vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; + vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; + ++numOut; + } - return numOut; + return numOut; } -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB) +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB) { - b2DistanceInput input; - input.proxyA.Set(shapeA, indexA); - input.proxyB.Set(shapeB, indexB); - input.transformA = xfA; - input.transformB = xfB; - input.useRadii = true; + b2DistanceInput input; + input.proxyA.Set(shapeA, indexA); + input.proxyB.Set(shapeB, indexB); + input.transformA = xfA; + input.transformB = xfB; + input.useRadii = true; - b2SimplexCache cache; - cache.count = 0; + b2SimplexCache cache; + cache.count = 0; - b2DistanceOutput output; + b2DistanceOutput output; - b2Distance(&output, &cache, &input); + b2Distance(&output, &cache, &input); - return output.distance < 10.0f * b2_epsilon; + return output.distance < 10.0f * b2_epsilon; } diff --git a/external/Box2D/Collision/b2Collision.h b/external/Box2D/Collision/b2Collision.h index 2e7386232b..ad023b3caa 100644 --- a/external/Box2D/Collision/b2Collision.h +++ b/external/Box2D/Collision/b2Collision.h @@ -20,7 +20,7 @@ #define B2_COLLISION_H #include -#include +#include /// @file /// Structures and functions used for computing contact points, distance @@ -37,23 +37,23 @@ const uint8 b2_nullFeature = UCHAR_MAX; /// This must be 4 bytes or less. struct b2ContactFeature { - enum Type - { - e_vertex = 0, - e_face = 1 - }; + enum Type + { + e_vertex = 0, + e_face = 1 + }; - uint8 indexA; ///< Feature index on shapeA - uint8 indexB; ///< Feature index on shapeB - uint8 typeA; ///< The feature type on shapeA - uint8 typeB; ///< The feature type on shapeB + uint8 indexA; ///< Feature index on shapeA + uint8 indexB; ///< Feature index on shapeB + uint8 typeA; ///< The feature type on shapeA + uint8 typeB; ///< The feature type on shapeB }; /// Contact ids to facilitate warm starting. union b2ContactID { - b2ContactFeature cf; - uint32 key; ///< Used to quickly compare contact ids. + b2ContactFeature cf; + uint32 key; ///< Used to quickly compare contact ids. }; /// A manifold point is a contact point belonging to a contact @@ -68,10 +68,10 @@ union b2ContactID /// provide reliable contact forces, especially for high speed collisions. struct b2ManifoldPoint { - b2Vec2 localPoint; ///< usage depends on manifold type - float32 normalImpulse; ///< the non-penetration impulse - float32 tangentImpulse; ///< the friction impulse - b2ContactID id; ///< uniquely identifies a contact point between two shapes + b2Vec2 localPoint; ///< usage depends on manifold type + float32 normalImpulse; ///< the non-penetration impulse + float32 tangentImpulse; ///< the friction impulse + b2ContactID id; ///< uniquely identifies a contact point between two shapes }; /// A manifold for two touching convex shapes. @@ -92,185 +92,186 @@ struct b2ManifoldPoint /// This structure is stored across time steps, so we keep it small. struct b2Manifold { - enum Type - { - e_circles, - e_faceA, - e_faceB - }; + enum Type + { + e_circles, + e_faceA, + e_faceB + }; - b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact - b2Vec2 localNormal; ///< not use for Type::e_points - b2Vec2 localPoint; ///< usage depends on manifold type - Type type; - int32 pointCount; ///< the number of manifold points + b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact + b2Vec2 localNormal; ///< not use for Type::e_points + b2Vec2 localPoint; ///< usage depends on manifold type + Type type; + int32 pointCount; ///< the number of manifold points }; /// This is used to compute the current state of a contact manifold. struct b2WorldManifold { - /// Evaluate the manifold with supplied transforms. This assumes - /// modest motion from the original state. This does not change the - /// point count, impulses, etc. The radii must come from the shapes - /// that generated the manifold. - void Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB); + /// Evaluate the manifold with supplied transforms. This assumes + /// modest motion from the original state. This does not change the + /// point count, impulses, etc. The radii must come from the shapes + /// that generated the manifold. + void Initialize(const b2Manifold* manifold, + const b2Transform& xfA, float32 radiusA, + const b2Transform& xfB, float32 radiusB); - b2Vec2 normal; ///< world vector pointing from A to B - b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) + b2Vec2 normal; ///< world vector pointing from A to B + b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) + float32 separations[b2_maxManifoldPoints]; ///< a negative value indicates overlap, in meters }; /// This is used for determining the state of contact points. enum b2PointState { - b2_nullState, ///< point does not exist - b2_addState, ///< point was added in the update - b2_persistState, ///< point persisted across the update - b2_removeState ///< point was removed in the update + b2_nullState, ///< point does not exist + b2_addState, ///< point was added in the update + b2_persistState, ///< point persisted across the update + b2_removeState ///< point was removed in the update }; /// Compute the point states given two manifolds. The states pertain to the transition from manifold1 /// to manifold2. So state1 is either persist or remove while state2 is either add or persist. void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2); + const b2Manifold* manifold1, const b2Manifold* manifold2); /// Used for computing contact manifolds. struct b2ClipVertex { - b2Vec2 v; - b2ContactID id; + b2Vec2 v; + b2ContactID id; }; /// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). struct b2RayCastInput { - b2Vec2 p1, p2; - float32 maxFraction; + b2Vec2 p1, p2; + float32 maxFraction; }; /// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 /// come from b2RayCastInput. struct b2RayCastOutput { - b2Vec2 normal; - float32 fraction; + b2Vec2 normal; + float32 fraction; }; /// An axis aligned bounding box. struct b2AABB { - /// Verify that the bounds are sorted. - bool IsValid() const; + /// Verify that the bounds are sorted. + bool IsValid() const; - /// Get the center of the AABB. - b2Vec2 GetCenter() const - { - return 0.5f * (lowerBound + upperBound); - } + /// Get the center of the AABB. + b2Vec2 GetCenter() const + { + return 0.5f * (lowerBound + upperBound); + } - /// Get the extents of the AABB (half-widths). - b2Vec2 GetExtents() const - { - return 0.5f * (upperBound - lowerBound); - } + /// Get the extents of the AABB (half-widths). + b2Vec2 GetExtents() const + { + return 0.5f * (upperBound - lowerBound); + } - /// Get the perimeter length - float32 GetPerimeter() const - { - float32 wx = upperBound.x - lowerBound.x; - float32 wy = upperBound.y - lowerBound.y; - return 2.0f * (wx + wy); - } + /// Get the perimeter length + float32 GetPerimeter() const + { + float32 wx = upperBound.x - lowerBound.x; + float32 wy = upperBound.y - lowerBound.y; + return 2.0f * (wx + wy); + } - /// Combine an AABB into this one. - void Combine(const b2AABB& aabb) - { - lowerBound = b2Min(lowerBound, aabb.lowerBound); - upperBound = b2Max(upperBound, aabb.upperBound); - } + /// Combine an AABB into this one. + void Combine(const b2AABB& aabb) + { + lowerBound = b2Min(lowerBound, aabb.lowerBound); + upperBound = b2Max(upperBound, aabb.upperBound); + } - /// Combine two AABBs into this one. - void Combine(const b2AABB& aabb1, const b2AABB& aabb2) - { - lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); - upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); - } + /// Combine two AABBs into this one. + void Combine(const b2AABB& aabb1, const b2AABB& aabb2) + { + lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); + upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); + } - /// Does this aabb contain the provided AABB. - bool Contains(const b2AABB& aabb) const - { - bool result = true; - result = result && lowerBound.x <= aabb.lowerBound.x; - result = result && lowerBound.y <= aabb.lowerBound.y; - result = result && aabb.upperBound.x <= upperBound.x; - result = result && aabb.upperBound.y <= upperBound.y; - return result; - } + /// Does this aabb contain the provided AABB. + bool Contains(const b2AABB& aabb) const + { + bool result = true; + result = result && lowerBound.x <= aabb.lowerBound.x; + result = result && lowerBound.y <= aabb.lowerBound.y; + result = result && aabb.upperBound.x <= upperBound.x; + result = result && aabb.upperBound.y <= upperBound.y; + return result; + } - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; - b2Vec2 lowerBound; ///< the lower vertex - b2Vec2 upperBound; ///< the upper vertex + b2Vec2 lowerBound; ///< the lower vertex + b2Vec2 upperBound; ///< the upper vertex }; /// Compute the collision manifold between two circles. void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); + const b2CircleShape* circleA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); /// Compute the collision manifold between a polygon and a circle. void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); /// Compute the collision manifold between two polygons. void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); + const b2PolygonShape* polygonA, const b2Transform& xfA, + const b2PolygonShape* polygonB, const b2Transform& xfB); /// Compute the collision manifold between an edge and a circle. void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); + const b2EdgeShape* polygonA, const b2Transform& xfA, + const b2CircleShape* circleB, const b2Transform& xfB); /// Compute the collision manifold between an edge and a circle. void b2CollideEdgeAndPolygon(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* circleB, const b2Transform& xfB); + const b2EdgeShape* edgeA, const b2Transform& xfA, + const b2PolygonShape* circleB, const b2Transform& xfB); /// Clipping for contact manifolds. int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA); + const b2Vec2& normal, float32 offset, int32 vertexIndexA); /// Determine if two generic shapes overlap. -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB); +bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, + const b2Shape* shapeB, int32 indexB, + const b2Transform& xfA, const b2Transform& xfB); // ---------------- Inline Functions ------------------------------------------ inline bool b2AABB::IsValid() const { - b2Vec2 d = upperBound - lowerBound; - bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && lowerBound.IsValid() && upperBound.IsValid(); - return valid; + b2Vec2 d = upperBound - lowerBound; + bool valid = d.x >= 0.0f && d.y >= 0.0f; + valid = valid && lowerBound.IsValid() && upperBound.IsValid(); + return valid; } inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) { - b2Vec2 d1, d2; - d1 = b.lowerBound - a.upperBound; - d2 = a.lowerBound - b.upperBound; + b2Vec2 d1, d2; + d1 = b.lowerBound - a.upperBound; + d2 = a.lowerBound - b.upperBound; - if (d1.x > 0.0f || d1.y > 0.0f) - return false; + if (d1.x > 0.0f || d1.y > 0.0f) + return false; - if (d2.x > 0.0f || d2.y > 0.0f) - return false; + if (d2.x > 0.0f || d2.y > 0.0f) + return false; - return true; + return true; } #endif diff --git a/external/Box2D/Collision/b2Distance.cpp b/external/Box2D/Collision/b2Distance.cpp index ac67d3be43..78daab3e2e 100644 --- a/external/Box2D/Collision/b2Distance.cpp +++ b/external/Box2D/Collision/b2Distance.cpp @@ -27,245 +27,246 @@ int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; void b2DistanceProxy::Set(const b2Shape* shape, int32 index) { - switch (shape->GetType()) - { - case b2Shape::e_circle: - { - const b2CircleShape* circle = (b2CircleShape*)shape; - m_vertices = &circle->m_p; - m_count = 1; - m_radius = circle->m_radius; - } - break; + switch (shape->GetType()) + { + case b2Shape::e_circle: + { + const b2CircleShape* circle = static_cast(shape); + m_vertices = &circle->m_p; + m_count = 1; + m_radius = circle->m_radius; + } + break; - case b2Shape::e_polygon: - { - const b2PolygonShape* polygon = (b2PolygonShape*)shape; - m_vertices = polygon->m_vertices; - m_count = polygon->m_vertexCount; - m_radius = polygon->m_radius; - } - break; + case b2Shape::e_polygon: + { + const b2PolygonShape* polygon = static_cast(shape); + m_vertices = polygon->m_vertices; + m_count = polygon->m_count; + m_radius = polygon->m_radius; + } + break; - case b2Shape::e_chain: - { - const b2ChainShape* chain = (b2ChainShape*)shape; - b2Assert(0 <= index && index < chain->m_count); + case b2Shape::e_chain: + { + const b2ChainShape* chain = static_cast(shape); + b2Assert(0 <= index && index < chain->m_count); - m_buffer[0] = chain->m_vertices[index]; - if (index + 1 < chain->m_count) - { - m_buffer[1] = chain->m_vertices[index + 1]; - } - else - { - m_buffer[1] = chain->m_vertices[0]; - } + m_buffer[0] = chain->m_vertices[index]; + if (index + 1 < chain->m_count) + { + m_buffer[1] = chain->m_vertices[index + 1]; + } + else + { + m_buffer[1] = chain->m_vertices[0]; + } - m_vertices = m_buffer; - m_count = 2; - m_radius = chain->m_radius; - } - break; + m_vertices = m_buffer; + m_count = 2; + m_radius = chain->m_radius; + } + break; - case b2Shape::e_edge: - { - const b2EdgeShape* edge = (b2EdgeShape*)shape; - m_vertices = &edge->m_vertex1; - m_count = 2; - m_radius = edge->m_radius; - } - break; + case b2Shape::e_edge: + { + const b2EdgeShape* edge = static_cast(shape); + m_vertices = &edge->m_vertex1; + m_count = 2; + m_radius = edge->m_radius; + } + break; - default: - b2Assert(false); - } + default: + b2Assert(false); + } } struct b2SimplexVertex { - b2Vec2 wA; // support point in proxyA - b2Vec2 wB; // support point in proxyB - b2Vec2 w; // wB - wA - float32 a; // barycentric coordinate for closest point - int32 indexA; // wA index - int32 indexB; // wB index + b2Vec2 wA; // support point in proxyA + b2Vec2 wB; // support point in proxyB + b2Vec2 w; // wB - wA + float32 a; // barycentric coordinate for closest point + int32 indexA; // wA index + int32 indexB; // wB index }; struct b2Simplex { - void ReadCache( const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Transform& transformA, - const b2DistanceProxy* proxyB, const b2Transform& transformB) - { - b2Assert(cache->count <= 3); - - // Copy data from cache. - m_count = cache->count; - b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - b2SimplexVertex* v = vertices + i; - v->indexA = cache->indexA[i]; - v->indexB = cache->indexB[i]; - b2Vec2 wALocal = proxyA->GetVertex(v->indexA); - b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - v->a = 0.0f; - } + void ReadCache( const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Transform& transformA, + const b2DistanceProxy* proxyB, const b2Transform& transformB) + { + b2Assert(cache->count <= 3); + + // Copy data from cache. + m_count = cache->count; + b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + b2SimplexVertex* v = vertices + i; + v->indexA = cache->indexA[i]; + v->indexB = cache->indexB[i]; + b2Vec2 wALocal = proxyA->GetVertex(v->indexA); + b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + v->a = 0.0f; + } - // Compute the new simplex metric, if it is substantially different than - // old metric then flush the simplex. - if (m_count > 1) - { - float32 metric1 = cache->metric; - float32 metric2 = GetMetric(); - if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) - { - // Reset the simplex. - m_count = 0; - } - } + // Compute the new simplex metric, if it is substantially different than + // old metric then flush the simplex. + if (m_count > 1) + { + float32 metric1 = cache->metric; + float32 metric2 = GetMetric(); + if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) + { + // Reset the simplex. + m_count = 0; + } + } - // If the cache is empty or invalid ... - if (m_count == 0) - { - b2SimplexVertex* v = vertices + 0; - v->indexA = 0; - v->indexB = 0; - b2Vec2 wALocal = proxyA->GetVertex(0); - b2Vec2 wBLocal = proxyB->GetVertex(0); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - m_count = 1; - } - } + // If the cache is empty or invalid ... + if (m_count == 0) + { + b2SimplexVertex* v = vertices + 0; + v->indexA = 0; + v->indexB = 0; + b2Vec2 wALocal = proxyA->GetVertex(0); + b2Vec2 wBLocal = proxyB->GetVertex(0); + v->wA = b2Mul(transformA, wALocal); + v->wB = b2Mul(transformB, wBLocal); + v->w = v->wB - v->wA; + v->a = 1.0f; + m_count = 1; + } + } - void WriteCache(b2SimplexCache* cache) const - { - cache->metric = GetMetric(); - cache->count = uint16(m_count); - const b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - cache->indexA[i] = uint8(vertices[i].indexA); - cache->indexB[i] = uint8(vertices[i].indexB); - } - } + void WriteCache(b2SimplexCache* cache) const + { + cache->metric = GetMetric(); + cache->count = uint16(m_count); + const b2SimplexVertex* vertices = &m_v1; + for (int32 i = 0; i < m_count; ++i) + { + cache->indexA[i] = uint8(vertices[i].indexA); + cache->indexB[i] = uint8(vertices[i].indexB); + } + } - b2Vec2 GetSearchDirection() const - { - switch (m_count) - { - case 1: - return -m_v1.w; + b2Vec2 GetSearchDirection() const + { + switch (m_count) + { + case 1: + return -m_v1.w; - case 2: - { - b2Vec2 e12 = m_v2.w - m_v1.w; - float32 sgn = b2Cross(e12, -m_v1.w); - if (sgn > 0.0f) - { - // Origin is left of e12. - return b2Cross(1.0f, e12); - } - else - { - // Origin is right of e12. - return b2Cross(e12, 1.0f); - } - } + case 2: + { + b2Vec2 e12 = m_v2.w - m_v1.w; + float32 sgn = b2Cross(e12, -m_v1.w); + if (sgn > 0.0f) + { + // Origin is left of e12. + return b2Cross(1.0f, e12); + } + else + { + // Origin is right of e12. + return b2Cross(e12, 1.0f); + } + } - default: - b2Assert(false); - return b2Vec2_zero; - } - } + default: + b2Assert(false); + return b2Vec2_zero; + } + } - b2Vec2 GetClosestPoint() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return b2Vec2_zero; + b2Vec2 GetClosestPoint() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return b2Vec2_zero; - case 1: - return m_v1.w; + case 1: + return m_v1.w; - case 2: - return m_v1.a * m_v1.w + m_v2.a * m_v2.w; + case 2: + return m_v1.a * m_v1.w + m_v2.a * m_v2.w; - case 3: - return b2Vec2_zero; + case 3: + return b2Vec2_zero; - default: - b2Assert(false); - return b2Vec2_zero; - } - } + default: + b2Assert(false); + return b2Vec2_zero; + } + } - void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const - { - switch (m_count) - { - case 0: - b2Assert(false); - break; + void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const + { + switch (m_count) + { + case 0: + b2Assert(false); + break; - case 1: - *pA = m_v1.wA; - *pB = m_v1.wB; - break; + case 1: + *pA = m_v1.wA; + *pB = m_v1.wB; + break; - case 2: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; - *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; - break; + case 2: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; + *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; + break; - case 3: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; - *pB = *pA; - break; + case 3: + *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; + *pB = *pA; + break; - default: - b2Assert(false); - break; - } - } + default: + b2Assert(false); + break; + } + } - float32 GetMetric() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return 0.0; + float32 GetMetric() const + { + switch (m_count) + { + case 0: + b2Assert(false); + return 0.0f; - case 1: - return 0.0f; + case 1: + return 0.0f; - case 2: - return b2Distance(m_v1.w, m_v2.w); + case 2: + return b2Distance(m_v1.w, m_v2.w); - case 3: - return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); + case 3: + return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); - default: - b2Assert(false); - return 0.0f; - } - } + default: + b2Assert(false); + return 0.0f; + } + } - void Solve2(); - void Solve3(); + void Solve2(); + void Solve3(); - b2SimplexVertex m_v1, m_v2, m_v3; - int32 m_count; + b2SimplexVertex m_v1, m_v2, m_v3; + int32 m_count; }; @@ -294,36 +295,36 @@ struct b2Simplex // a2 = d12_2 / d12 void b2Simplex::Solve2() { - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 e12 = w2 - w1; + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 e12 = w2 - w1; - // w1 region - float32 d12_2 = -b2Dot(w1, e12); - if (d12_2 <= 0.0f) - { - // a2 <= 0, so we clamp it to 0 - m_v1.a = 1.0f; - m_count = 1; - return; - } + // w1 region + float32 d12_2 = -b2Dot(w1, e12); + if (d12_2 <= 0.0f) + { + // a2 <= 0, so we clamp it to 0 + m_v1.a = 1.0f; + m_count = 1; + return; + } - // w2 region - float32 d12_1 = b2Dot(w2, e12); - if (d12_1 <= 0.0f) - { - // a1 <= 0, so we clamp it to 0 - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } + // w2 region + float32 d12_1 = b2Dot(w2, e12); + if (d12_1 <= 0.0f) + { + // a1 <= 0, so we clamp it to 0 + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } - // Must be in e12 region. - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; + // Must be in e12 region. + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; } // Possible regions: @@ -333,271 +334,270 @@ void b2Simplex::Solve2() // - inside the triangle void b2Simplex::Solve3() { - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 w3 = m_v3.w; + b2Vec2 w1 = m_v1.w; + b2Vec2 w2 = m_v2.w; + b2Vec2 w3 = m_v3.w; - // Edge12 - // [1 1 ][a1] = [1] - // [w1.e12 w2.e12][a2] = [0] - // a3 = 0 - b2Vec2 e12 = w2 - w1; - float32 w1e12 = b2Dot(w1, e12); - float32 w2e12 = b2Dot(w2, e12); - float32 d12_1 = w2e12; - float32 d12_2 = -w1e12; + // Edge12 + // [1 1 ][a1] = [1] + // [w1.e12 w2.e12][a2] = [0] + // a3 = 0 + b2Vec2 e12 = w2 - w1; + float32 w1e12 = b2Dot(w1, e12); + float32 w2e12 = b2Dot(w2, e12); + float32 d12_1 = w2e12; + float32 d12_2 = -w1e12; - // Edge13 - // [1 1 ][a1] = [1] - // [w1.e13 w3.e13][a3] = [0] - // a2 = 0 - b2Vec2 e13 = w3 - w1; - float32 w1e13 = b2Dot(w1, e13); - float32 w3e13 = b2Dot(w3, e13); - float32 d13_1 = w3e13; - float32 d13_2 = -w1e13; + // Edge13 + // [1 1 ][a1] = [1] + // [w1.e13 w3.e13][a3] = [0] + // a2 = 0 + b2Vec2 e13 = w3 - w1; + float32 w1e13 = b2Dot(w1, e13); + float32 w3e13 = b2Dot(w3, e13); + float32 d13_1 = w3e13; + float32 d13_2 = -w1e13; - // Edge23 - // [1 1 ][a2] = [1] - // [w2.e23 w3.e23][a3] = [0] - // a1 = 0 - b2Vec2 e23 = w3 - w2; - float32 w2e23 = b2Dot(w2, e23); - float32 w3e23 = b2Dot(w3, e23); - float32 d23_1 = w3e23; - float32 d23_2 = -w2e23; - - // Triangle123 - float32 n123 = b2Cross(e12, e13); + // Edge23 + // [1 1 ][a2] = [1] + // [w2.e23 w3.e23][a3] = [0] + // a1 = 0 + b2Vec2 e23 = w3 - w2; + float32 w2e23 = b2Dot(w2, e23); + float32 w3e23 = b2Dot(w3, e23); + float32 d23_1 = w3e23; + float32 d23_2 = -w2e23; + + // Triangle123 + float32 n123 = b2Cross(e12, e13); - float32 d123_1 = n123 * b2Cross(w2, w3); - float32 d123_2 = n123 * b2Cross(w3, w1); - float32 d123_3 = n123 * b2Cross(w1, w2); + float32 d123_1 = n123 * b2Cross(w2, w3); + float32 d123_2 = n123 * b2Cross(w3, w1); + float32 d123_3 = n123 * b2Cross(w1, w2); - // w1 region - if (d12_2 <= 0.0f && d13_2 <= 0.0f) - { - m_v1.a = 1.0f; - m_count = 1; - return; - } + // w1 region + if (d12_2 <= 0.0f && d13_2 <= 0.0f) + { + m_v1.a = 1.0f; + m_count = 1; + return; + } - // e12 - if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) - { - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; - return; - } + // e12 + if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) + { + float32 inv_d12 = 1.0f / (d12_1 + d12_2); + m_v1.a = d12_1 * inv_d12; + m_v2.a = d12_2 * inv_d12; + m_count = 2; + return; + } - // e13 - if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) - { - float32 inv_d13 = 1.0f / (d13_1 + d13_2); - m_v1.a = d13_1 * inv_d13; - m_v3.a = d13_2 * inv_d13; - m_count = 2; - m_v2 = m_v3; - return; - } + // e13 + if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) + { + float32 inv_d13 = 1.0f / (d13_1 + d13_2); + m_v1.a = d13_1 * inv_d13; + m_v3.a = d13_2 * inv_d13; + m_count = 2; + m_v2 = m_v3; + return; + } - // w2 region - if (d12_1 <= 0.0f && d23_2 <= 0.0f) - { - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } + // w2 region + if (d12_1 <= 0.0f && d23_2 <= 0.0f) + { + m_v2.a = 1.0f; + m_count = 1; + m_v1 = m_v2; + return; + } - // w3 region - if (d13_1 <= 0.0f && d23_1 <= 0.0f) - { - m_v3.a = 1.0f; - m_count = 1; - m_v1 = m_v3; - return; - } + // w3 region + if (d13_1 <= 0.0f && d23_1 <= 0.0f) + { + m_v3.a = 1.0f; + m_count = 1; + m_v1 = m_v3; + return; + } - // e23 - if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) - { - float32 inv_d23 = 1.0f / (d23_1 + d23_2); - m_v2.a = d23_1 * inv_d23; - m_v3.a = d23_2 * inv_d23; - m_count = 2; - m_v1 = m_v3; - return; - } + // e23 + if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) + { + float32 inv_d23 = 1.0f / (d23_1 + d23_2); + m_v2.a = d23_1 * inv_d23; + m_v3.a = d23_2 * inv_d23; + m_count = 2; + m_v1 = m_v3; + return; + } - // Must be in triangle123 - float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); - m_v1.a = d123_1 * inv_d123; - m_v2.a = d123_2 * inv_d123; - m_v3.a = d123_3 * inv_d123; - m_count = 3; + // Must be in triangle123 + float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); + m_v1.a = d123_1 * inv_d123; + m_v2.a = d123_2 * inv_d123; + m_v3.a = d123_3 * inv_d123; + m_count = 3; } void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input) + b2SimplexCache* cache, + const b2DistanceInput* input) { - ++b2_gjkCalls; + ++b2_gjkCalls; - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; - b2Transform transformA = input->transformA; - b2Transform transformB = input->transformB; + b2Transform transformA = input->transformA; + b2Transform transformB = input->transformB; - // Initialize the simplex. - b2Simplex simplex; - simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); + // Initialize the simplex. + b2Simplex simplex; + simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); - // Get simplex vertices as an array. - b2SimplexVertex* vertices = &simplex.m_v1; - const int32 k_maxIters = 20; + // Get simplex vertices as an array. + b2SimplexVertex* vertices = &simplex.m_v1; + const int32 k_maxIters = 20; - // These store the vertices of the last simplex so that we - // can check for duplicates and prevent cycling. - int32 saveA[3], saveB[3]; - int32 saveCount = 0; + // These store the vertices of the last simplex so that we + // can check for duplicates and prevent cycling. + int32 saveA[3], saveB[3]; + int32 saveCount = 0; - b2Vec2 closestPoint = simplex.GetClosestPoint(); - float32 distanceSqr1 = closestPoint.LengthSquared(); - float32 distanceSqr2 = distanceSqr1; + float32 distanceSqr1 = b2_maxFloat; + float32 distanceSqr2 = distanceSqr1; - // Main iteration loop. - int32 iter = 0; - while (iter < k_maxIters) - { - // Copy simplex so we can identify duplicates. - saveCount = simplex.m_count; - for (int32 i = 0; i < saveCount; ++i) - { - saveA[i] = vertices[i].indexA; - saveB[i] = vertices[i].indexB; - } + // Main iteration loop. + int32 iter = 0; + while (iter < k_maxIters) + { + // Copy simplex so we can identify duplicates. + saveCount = simplex.m_count; + for (int32 i = 0; i < saveCount; ++i) + { + saveA[i] = vertices[i].indexA; + saveB[i] = vertices[i].indexB; + } - switch (simplex.m_count) - { - case 1: - break; + switch (simplex.m_count) + { + case 1: + break; - case 2: - simplex.Solve2(); - break; + case 2: + simplex.Solve2(); + break; - case 3: - simplex.Solve3(); - break; + case 3: + simplex.Solve3(); + break; - default: - b2Assert(false); - } + default: + b2Assert(false); + } - // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.m_count == 3) - { - break; - } + // If we have 3 points, then the origin is in the corresponding triangle. + if (simplex.m_count == 3) + { + break; + } - // Compute closest point. - b2Vec2 p = simplex.GetClosestPoint(); - distanceSqr2 = p.LengthSquared(); + // Compute closest point. + b2Vec2 p = simplex.GetClosestPoint(); + distanceSqr2 = p.LengthSquared(); - // Ensure progress - if (distanceSqr2 >= distanceSqr1) - { - //break; - } - distanceSqr1 = distanceSqr2; + // Ensure progress + if (distanceSqr2 >= distanceSqr1) + { + //break; + } + distanceSqr1 = distanceSqr2; - // Get search direction. - b2Vec2 d = simplex.GetSearchDirection(); + // Get search direction. + b2Vec2 d = simplex.GetSearchDirection(); - // Ensure the search direction is numerically fit. - if (d.LengthSquared() < b2_epsilon * b2_epsilon) - { - // The origin is probably contained by a line segment - // or triangle. Thus the shapes are overlapped. + // Ensure the search direction is numerically fit. + if (d.LengthSquared() < b2_epsilon * b2_epsilon) + { + // The origin is probably contained by a line segment + // or triangle. Thus the shapes are overlapped. - // We can't return zero here even though there may be overlap. - // In case the simplex is a point, segment, or triangle it is difficult - // to determine if the origin is contained in the CSO or very close to it. - break; - } + // We can't return zero here even though there may be overlap. + // In case the simplex is a point, segment, or triangle it is difficult + // to determine if the origin is contained in the CSO or very close to it. + break; + } - // Compute a tentative new simplex vertex using support points. - b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); - vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); - b2Vec2 wBLocal; - vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); - vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); - vertex->w = vertex->wB - vertex->wA; + // Compute a tentative new simplex vertex using support points. + b2SimplexVertex* vertex = vertices + simplex.m_count; + vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); + vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); + b2Vec2 wBLocal; + vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); + vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); + vertex->w = vertex->wB - vertex->wA; - // Iteration count is equated to the number of support point calls. - ++iter; - ++b2_gjkIters; + // Iteration count is equated to the number of support point calls. + ++iter; + ++b2_gjkIters; - // Check for duplicate support points. This is the main termination criteria. - bool duplicate = false; - for (int32 i = 0; i < saveCount; ++i) - { - if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) - { - duplicate = true; - break; - } - } + // Check for duplicate support points. This is the main termination criteria. + bool duplicate = false; + for (int32 i = 0; i < saveCount; ++i) + { + if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) + { + duplicate = true; + break; + } + } - // If we found a duplicate support point we must exit to avoid cycling. - if (duplicate) - { - break; - } + // If we found a duplicate support point we must exit to avoid cycling. + if (duplicate) + { + break; + } - // New vertex is ok and needed. - ++simplex.m_count; - } + // New vertex is ok and needed. + ++simplex.m_count; + } - b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); + b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); - // Prepare output. - simplex.GetWitnessPoints(&output->pointA, &output->pointB); - output->distance = b2Distance(output->pointA, output->pointB); - output->iterations = iter; + // Prepare output. + simplex.GetWitnessPoints(&output->pointA, &output->pointB); + output->distance = b2Distance(output->pointA, output->pointB); + output->iterations = iter; - // Cache the simplex. - simplex.WriteCache(cache); + // Cache the simplex. + simplex.WriteCache(cache); - // Apply radii if requested. - if (input->useRadii) - { - float32 rA = proxyA->m_radius; - float32 rB = proxyB->m_radius; + // Apply radii if requested. + if (input->useRadii) + { + float32 rA = proxyA->m_radius; + float32 rB = proxyB->m_radius; - if (output->distance > rA + rB && output->distance > b2_epsilon) - { - // Shapes are still no overlapped. - // Move the witness points to the outer surface. - output->distance -= rA + rB; - b2Vec2 normal = output->pointB - output->pointA; - normal.Normalize(); - output->pointA += rA * normal; - output->pointB -= rB * normal; - } - else - { - // Shapes are overlapped when radii are considered. - // Move the witness points to the middle. - b2Vec2 p = 0.5f * (output->pointA + output->pointB); - output->pointA = p; - output->pointB = p; - output->distance = 0.0f; - } - } + if (output->distance > rA + rB && output->distance > b2_epsilon) + { + // Shapes are still no overlapped. + // Move the witness points to the outer surface. + output->distance -= rA + rB; + b2Vec2 normal = output->pointB - output->pointA; + normal.Normalize(); + output->pointA += rA * normal; + output->pointB -= rB * normal; + } + else + { + // Shapes are overlapped when radii are considered. + // Move the witness points to the middle. + b2Vec2 p = 0.5f * (output->pointA + output->pointB); + output->pointA = p; + output->pointB = p; + output->distance = 0.0f; + } + } } diff --git a/external/Box2D/Collision/b2Distance.h b/external/Box2D/Collision/b2Distance.h index d598b7339d..7bae689d15 100644 --- a/external/Box2D/Collision/b2Distance.h +++ b/external/Box2D/Collision/b2Distance.h @@ -28,38 +28,38 @@ class b2Shape; /// It encapsulates any shape. struct b2DistanceProxy { - b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} + b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} - /// Initialize the proxy using the given shape. The shape - /// must remain in scope while the proxy is in use. - void Set(const b2Shape* shape, int32 index); + /// Initialize the proxy using the given shape. The shape + /// must remain in scope while the proxy is in use. + void Set(const b2Shape* shape, int32 index); - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; + /// Get the supporting vertex index in the given direction. + int32 GetSupport(const b2Vec2& d) const; - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; + /// Get the supporting vertex in the given direction. + const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - /// Get the vertex count. - int32 GetVertexCount() const; + /// Get the vertex count. + int32 GetVertexCount() const; - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; + /// Get a vertex by index. Used by b2Distance. + const b2Vec2& GetVertex(int32 index) const; - b2Vec2 m_buffer[2]; - const b2Vec2* m_vertices; - int32 m_count; - float32 m_radius; + b2Vec2 m_buffer[2]; + const b2Vec2* m_vertices; + int32 m_count; + float32 m_radius; }; /// Used to warm start b2Distance. /// Set count to zero on first call. struct b2SimplexCache { - float32 metric; ///< length or area - uint16 count; - uint8 indexA[3]; ///< vertices on shape A - uint8 indexB[3]; ///< vertices on shape B + float32 metric; ///< length or area + uint16 count; + uint8 indexA[3]; ///< vertices on shape A + uint8 indexB[3]; ///< vertices on shape B }; /// Input for b2Distance. @@ -67,75 +67,75 @@ struct b2SimplexCache /// in the computation. Even struct b2DistanceInput { - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Transform transformA; - b2Transform transformB; - bool useRadii; + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Transform transformA; + b2Transform transformB; + bool useRadii; }; /// Output for b2Distance. struct b2DistanceOutput { - b2Vec2 pointA; ///< closest point on shapeA - b2Vec2 pointB; ///< closest point on shapeB - float32 distance; - int32 iterations; ///< number of GJK iterations used + b2Vec2 pointA; ///< closest point on shapeA + b2Vec2 pointB; ///< closest point on shapeB + float32 distance; + int32 iterations; ///< number of GJK iterations used }; /// Compute the closest points between two shapes. Supports any combination of: /// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. /// On the first call set b2SimplexCache.count to zero. void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input); + b2SimplexCache* cache, + const b2DistanceInput* input); ////////////////////////////////////////////////////////////////////////// inline int32 b2DistanceProxy::GetVertexCount() const { - return m_count; + return m_count; } inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const { - b2Assert(0 <= index && index < m_count); - return m_vertices[index]; + b2Assert(0 <= index && index < m_count); + return m_vertices[index]; } inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const { - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } - return bestIndex; + return bestIndex; } inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const { - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } + int32 bestIndex = 0; + float32 bestValue = b2Dot(m_vertices[0], d); + for (int32 i = 1; i < m_count; ++i) + { + float32 value = b2Dot(m_vertices[i], d); + if (value > bestValue) + { + bestIndex = i; + bestValue = value; + } + } - return m_vertices[bestIndex]; + return m_vertices[bestIndex]; } #endif diff --git a/external/Box2D/Collision/b2DynamicTree.cpp b/external/Box2D/Collision/b2DynamicTree.cpp index d1d53297e2..7035ab8b84 100644 --- a/external/Box2D/Collision/b2DynamicTree.cpp +++ b/external/Box2D/Collision/b2DynamicTree.cpp @@ -17,93 +17,86 @@ */ #include -#include -#ifndef SHP -#include -#else -#include -#endif -using namespace std; - +#include b2DynamicTree::b2DynamicTree() { - m_root = b2_nullNode; + m_root = b2_nullNode; - m_nodeCapacity = 16; - m_nodeCount = 0; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); + m_nodeCapacity = 16; + m_nodeCount = 0; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); - // Build a linked list for the free list. - for (int32 i = 0; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = 0; + // Build a linked list for the free list. + for (int32 i = 0; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = 0; - m_path = 0; + m_path = 0; - m_insertionCount = 0; + m_insertionCount = 0; } b2DynamicTree::~b2DynamicTree() { - // This frees the entire tree in one shot. - b2Free(m_nodes); + // This frees the entire tree in one shot. + b2Free(m_nodes); } // Allocate a node from the pool. Grow the pool if necessary. int32 b2DynamicTree::AllocateNode() { - // Expand the node pool as needed. - if (m_freeList == b2_nullNode) - { - b2Assert(m_nodeCount == m_nodeCapacity); + // Expand the node pool as needed. + if (m_freeList == b2_nullNode) + { + b2Assert(m_nodeCount == m_nodeCapacity); - // The free list is empty. Rebuild a bigger pool. - b2TreeNode* oldNodes = m_nodes; - m_nodeCapacity *= 2; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); - b2Free(oldNodes); + // The free list is empty. Rebuild a bigger pool. + b2TreeNode* oldNodes = m_nodes; + m_nodeCapacity *= 2; + m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); + memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); + b2Free(oldNodes); - // Build a linked list for the free list. The parent - // pointer becomes the "next" pointer. - for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = m_nodeCount; - } + // Build a linked list for the free list. The parent + // pointer becomes the "next" pointer. + for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) + { + m_nodes[i].next = i + 1; + m_nodes[i].height = -1; + } + m_nodes[m_nodeCapacity-1].next = b2_nullNode; + m_nodes[m_nodeCapacity-1].height = -1; + m_freeList = m_nodeCount; + } - // Peel a node off the free list. - int32 nodeId = m_freeList; - m_freeList = m_nodes[nodeId].next; - m_nodes[nodeId].parent = b2_nullNode; - m_nodes[nodeId].child1 = b2_nullNode; - m_nodes[nodeId].child2 = b2_nullNode; - m_nodes[nodeId].height = 0; - m_nodes[nodeId].userData = NULL; - ++m_nodeCount; - return nodeId; + // Peel a node off the free list. + int32 nodeId = m_freeList; + m_freeList = m_nodes[nodeId].next; + m_nodes[nodeId].parent = b2_nullNode; + m_nodes[nodeId].child1 = b2_nullNode; + m_nodes[nodeId].child2 = b2_nullNode; + m_nodes[nodeId].height = 0; + m_nodes[nodeId].userData = NULL; + ++m_nodeCount; + return nodeId; } // Return a node to the pool. void b2DynamicTree::FreeNode(int32 nodeId) { - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2Assert(0 < m_nodeCount); - m_nodes[nodeId].next = m_freeList; - m_nodes[nodeId].height = -1; - m_freeList = nodeId; - --m_nodeCount; + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2Assert(0 < m_nodeCount); + m_nodes[nodeId].next = m_freeList; + m_nodes[nodeId].height = -1; + m_freeList = nodeId; + --m_nodeCount; } // Create a proxy in the tree as a leaf node. We return the index @@ -111,665 +104,675 @@ void b2DynamicTree::FreeNode(int32 nodeId) // the node pool. int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) { - int32 proxyId = AllocateNode(); + int32 proxyId = AllocateNode(); - // Fatten the aabb. - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; - m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; - m_nodes[proxyId].userData = userData; - m_nodes[proxyId].height = 0; + // Fatten the aabb. + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; + m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; + m_nodes[proxyId].userData = userData; + m_nodes[proxyId].height = 0; - InsertLeaf(proxyId); + InsertLeaf(proxyId); - return proxyId; + return proxyId; } void b2DynamicTree::DestroyProxy(int32 proxyId) { - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - b2Assert(m_nodes[proxyId].IsLeaf()); + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + b2Assert(m_nodes[proxyId].IsLeaf()); - RemoveLeaf(proxyId); - FreeNode(proxyId); + RemoveLeaf(proxyId); + FreeNode(proxyId); } bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) { - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - b2Assert(m_nodes[proxyId].IsLeaf()); + b2Assert(m_nodes[proxyId].IsLeaf()); - if (m_nodes[proxyId].aabb.Contains(aabb)) - { - return false; - } + if (m_nodes[proxyId].aabb.Contains(aabb)) + { + return false; + } - RemoveLeaf(proxyId); + RemoveLeaf(proxyId); - // Extend AABB. - b2AABB b = aabb; - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - b.lowerBound = b.lowerBound - r; - b.upperBound = b.upperBound + r; + // Extend AABB. + b2AABB b = aabb; + b2Vec2 r(b2_aabbExtension, b2_aabbExtension); + b.lowerBound = b.lowerBound - r; + b.upperBound = b.upperBound + r; - // Predict AABB displacement. - b2Vec2 d = b2_aabbMultiplier * displacement; + // Predict AABB displacement. + b2Vec2 d = b2_aabbMultiplier * displacement; - if (d.x < 0.0f) - { - b.lowerBound.x += d.x; - } - else - { - b.upperBound.x += d.x; - } + if (d.x < 0.0f) + { + b.lowerBound.x += d.x; + } + else + { + b.upperBound.x += d.x; + } - if (d.y < 0.0f) - { - b.lowerBound.y += d.y; - } - else - { - b.upperBound.y += d.y; - } + if (d.y < 0.0f) + { + b.lowerBound.y += d.y; + } + else + { + b.upperBound.y += d.y; + } - m_nodes[proxyId].aabb = b; + m_nodes[proxyId].aabb = b; - InsertLeaf(proxyId); - return true; + InsertLeaf(proxyId); + return true; } void b2DynamicTree::InsertLeaf(int32 leaf) { - ++m_insertionCount; + ++m_insertionCount; - if (m_root == b2_nullNode) - { - m_root = leaf; - m_nodes[m_root].parent = b2_nullNode; - return; - } + if (m_root == b2_nullNode) + { + m_root = leaf; + m_nodes[m_root].parent = b2_nullNode; + return; + } - // Find the best sibling for this node - b2AABB leafAABB = m_nodes[leaf].aabb; - int32 index = m_root; - while (m_nodes[index].IsLeaf() == false) - { - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; + // Find the best sibling for this node + b2AABB leafAABB = m_nodes[leaf].aabb; + int32 index = m_root; + while (m_nodes[index].IsLeaf() == false) + { + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; - float32 area = m_nodes[index].aabb.GetPerimeter(); + float32 area = m_nodes[index].aabb.GetPerimeter(); - b2AABB combinedAABB; - combinedAABB.Combine(m_nodes[index].aabb, leafAABB); - float32 combinedArea = combinedAABB.GetPerimeter(); + b2AABB combinedAABB; + combinedAABB.Combine(m_nodes[index].aabb, leafAABB); + float32 combinedArea = combinedAABB.GetPerimeter(); - // Cost of creating a new parent for this node and the new leaf - float32 cost = 2.0f * combinedArea; + // Cost of creating a new parent for this node and the new leaf + float32 cost = 2.0f * combinedArea; - // Minimum cost of pushing the leaf further down the tree - float32 inheritanceCost = 2.0f * (combinedArea - area); + // Minimum cost of pushing the leaf further down the tree + float32 inheritanceCost = 2.0f * (combinedArea - area); - // Cost of descending into child1 - float32 cost1; - if (m_nodes[child1].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - cost1 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost1 = (newArea - oldArea) + inheritanceCost; - } + // Cost of descending into child1 + float32 cost1; + if (m_nodes[child1].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + cost1 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child1].aabb); + float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost1 = (newArea - oldArea) + inheritanceCost; + } - // Cost of descending into child2 - float32 cost2; - if (m_nodes[child2].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - cost2 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost2 = newArea - oldArea + inheritanceCost; - } + // Cost of descending into child2 + float32 cost2; + if (m_nodes[child2].IsLeaf()) + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + cost2 = aabb.GetPerimeter() + inheritanceCost; + } + else + { + b2AABB aabb; + aabb.Combine(leafAABB, m_nodes[child2].aabb); + float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); + float32 newArea = aabb.GetPerimeter(); + cost2 = newArea - oldArea + inheritanceCost; + } - // Descend according to the minimum cost. - if (cost < cost1 && cost < cost2) - { - break; - } + // Descend according to the minimum cost. + if (cost < cost1 && cost < cost2) + { + break; + } - // Descend - if (cost1 < cost2) - { - index = child1; - } - else - { - index = child2; - } - } + // Descend + if (cost1 < cost2) + { + index = child1; + } + else + { + index = child2; + } + } - int32 sibling = index; + int32 sibling = index; - // Create a new parent. - int32 oldParent = m_nodes[sibling].parent; - int32 newParent = AllocateNode(); - m_nodes[newParent].parent = oldParent; - m_nodes[newParent].userData = NULL; - m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); - m_nodes[newParent].height = m_nodes[sibling].height + 1; + // Create a new parent. + int32 oldParent = m_nodes[sibling].parent; + int32 newParent = AllocateNode(); + m_nodes[newParent].parent = oldParent; + m_nodes[newParent].userData = NULL; + m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); + m_nodes[newParent].height = m_nodes[sibling].height + 1; - if (oldParent != b2_nullNode) - { - // The sibling was not the root. - if (m_nodes[oldParent].child1 == sibling) - { - m_nodes[oldParent].child1 = newParent; - } - else - { - m_nodes[oldParent].child2 = newParent; - } + if (oldParent != b2_nullNode) + { + // The sibling was not the root. + if (m_nodes[oldParent].child1 == sibling) + { + m_nodes[oldParent].child1 = newParent; + } + else + { + m_nodes[oldParent].child2 = newParent; + } - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - } - else - { - // The sibling was the root. - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - m_root = newParent; - } + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + } + else + { + // The sibling was the root. + m_nodes[newParent].child1 = sibling; + m_nodes[newParent].child2 = leaf; + m_nodes[sibling].parent = newParent; + m_nodes[leaf].parent = newParent; + m_root = newParent; + } - // Walk back up the tree fixing heights and AABBs - index = m_nodes[leaf].parent; - while (index != b2_nullNode) - { - index = Balance(index); + // Walk back up the tree fixing heights and AABBs + index = m_nodes[leaf].parent; + while (index != b2_nullNode) + { + index = Balance(index); - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; - b2Assert(child1 != b2_nullNode); - b2Assert(child2 != b2_nullNode); + b2Assert(child1 != b2_nullNode); + b2Assert(child2 != b2_nullNode); - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - index = m_nodes[index].parent; - } + index = m_nodes[index].parent; + } - //Validate(); + //Validate(); } void b2DynamicTree::RemoveLeaf(int32 leaf) { - if (leaf == m_root) - { - m_root = b2_nullNode; - return; - } + if (leaf == m_root) + { + m_root = b2_nullNode; + return; + } - int32 parent = m_nodes[leaf].parent; - int32 grandParent = m_nodes[parent].parent; - int32 sibling; - if (m_nodes[parent].child1 == leaf) - { - sibling = m_nodes[parent].child2; - } - else - { - sibling = m_nodes[parent].child1; - } + int32 parent = m_nodes[leaf].parent; + int32 grandParent = m_nodes[parent].parent; + int32 sibling; + if (m_nodes[parent].child1 == leaf) + { + sibling = m_nodes[parent].child2; + } + else + { + sibling = m_nodes[parent].child1; + } - if (grandParent != b2_nullNode) - { - // Destroy parent and connect sibling to grandParent. - if (m_nodes[grandParent].child1 == parent) - { - m_nodes[grandParent].child1 = sibling; - } - else - { - m_nodes[grandParent].child2 = sibling; - } - m_nodes[sibling].parent = grandParent; - FreeNode(parent); + if (grandParent != b2_nullNode) + { + // Destroy parent and connect sibling to grandParent. + if (m_nodes[grandParent].child1 == parent) + { + m_nodes[grandParent].child1 = sibling; + } + else + { + m_nodes[grandParent].child2 = sibling; + } + m_nodes[sibling].parent = grandParent; + FreeNode(parent); - // Adjust ancestor bounds. - int32 index = grandParent; - while (index != b2_nullNode) - { - index = Balance(index); + // Adjust ancestor bounds. + int32 index = grandParent; + while (index != b2_nullNode) + { + index = Balance(index); - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; + int32 child1 = m_nodes[index].child1; + int32 child2 = m_nodes[index].child2; - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); + m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - index = m_nodes[index].parent; - } - } - else - { - m_root = sibling; - m_nodes[sibling].parent = b2_nullNode; - FreeNode(parent); - } + index = m_nodes[index].parent; + } + } + else + { + m_root = sibling; + m_nodes[sibling].parent = b2_nullNode; + FreeNode(parent); + } - //Validate(); + //Validate(); } // Perform a left or right rotation if node A is imbalanced. // Returns the new root index. int32 b2DynamicTree::Balance(int32 iA) { - b2Assert(iA != b2_nullNode); + b2Assert(iA != b2_nullNode); - b2TreeNode* A = m_nodes + iA; - if (A->IsLeaf() || A->height < 2) - { - return iA; - } + b2TreeNode* A = m_nodes + iA; + if (A->IsLeaf() || A->height < 2) + { + return iA; + } - int32 iB = A->child1; - int32 iC = A->child2; - b2Assert(0 <= iB && iB < m_nodeCapacity); - b2Assert(0 <= iC && iC < m_nodeCapacity); + int32 iB = A->child1; + int32 iC = A->child2; + b2Assert(0 <= iB && iB < m_nodeCapacity); + b2Assert(0 <= iC && iC < m_nodeCapacity); - b2TreeNode* B = m_nodes + iB; - b2TreeNode* C = m_nodes + iC; + b2TreeNode* B = m_nodes + iB; + b2TreeNode* C = m_nodes + iC; - int32 balance = C->height - B->height; + int32 balance = C->height - B->height; - // Rotate C up - if (balance > 1) - { - int32 iF = C->child1; - int32 iG = C->child2; - b2TreeNode* F = m_nodes + iF; - b2TreeNode* G = m_nodes + iG; - b2Assert(0 <= iF && iF < m_nodeCapacity); - b2Assert(0 <= iG && iG < m_nodeCapacity); + // Rotate C up + if (balance > 1) + { + int32 iF = C->child1; + int32 iG = C->child2; + b2TreeNode* F = m_nodes + iF; + b2TreeNode* G = m_nodes + iG; + b2Assert(0 <= iF && iF < m_nodeCapacity); + b2Assert(0 <= iG && iG < m_nodeCapacity); - // Swap A and C - C->child1 = iA; - C->parent = A->parent; - A->parent = iC; + // Swap A and C + C->child1 = iA; + C->parent = A->parent; + A->parent = iC; - // A's old parent should point to C - if (C->parent != b2_nullNode) - { - if (m_nodes[C->parent].child1 == iA) - { - m_nodes[C->parent].child1 = iC; - } - else - { - b2Assert(m_nodes[C->parent].child2 == iA); - m_nodes[C->parent].child2 = iC; - } - } - else - { - m_root = iC; - } + // A's old parent should point to C + if (C->parent != b2_nullNode) + { + if (m_nodes[C->parent].child1 == iA) + { + m_nodes[C->parent].child1 = iC; + } + else + { + b2Assert(m_nodes[C->parent].child2 == iA); + m_nodes[C->parent].child2 = iC; + } + } + else + { + m_root = iC; + } - // Rotate - if (F->height > G->height) - { - C->child2 = iF; - A->child2 = iG; - G->parent = iA; - A->aabb.Combine(B->aabb, G->aabb); - C->aabb.Combine(A->aabb, F->aabb); + // Rotate + if (F->height > G->height) + { + C->child2 = iF; + A->child2 = iG; + G->parent = iA; + A->aabb.Combine(B->aabb, G->aabb); + C->aabb.Combine(A->aabb, F->aabb); - A->height = 1 + b2Max(B->height, G->height); - C->height = 1 + b2Max(A->height, F->height); - } - else - { - C->child2 = iG; - A->child2 = iF; - F->parent = iA; - A->aabb.Combine(B->aabb, F->aabb); - C->aabb.Combine(A->aabb, G->aabb); + A->height = 1 + b2Max(B->height, G->height); + C->height = 1 + b2Max(A->height, F->height); + } + else + { + C->child2 = iG; + A->child2 = iF; + F->parent = iA; + A->aabb.Combine(B->aabb, F->aabb); + C->aabb.Combine(A->aabb, G->aabb); - A->height = 1 + b2Max(B->height, F->height); - C->height = 1 + b2Max(A->height, G->height); - } + A->height = 1 + b2Max(B->height, F->height); + C->height = 1 + b2Max(A->height, G->height); + } - return iC; - } - - // Rotate B up - if (balance < -1) - { - int32 iD = B->child1; - int32 iE = B->child2; - b2TreeNode* D = m_nodes + iD; - b2TreeNode* E = m_nodes + iE; - b2Assert(0 <= iD && iD < m_nodeCapacity); - b2Assert(0 <= iE && iE < m_nodeCapacity); + return iC; + } + + // Rotate B up + if (balance < -1) + { + int32 iD = B->child1; + int32 iE = B->child2; + b2TreeNode* D = m_nodes + iD; + b2TreeNode* E = m_nodes + iE; + b2Assert(0 <= iD && iD < m_nodeCapacity); + b2Assert(0 <= iE && iE < m_nodeCapacity); - // Swap A and B - B->child1 = iA; - B->parent = A->parent; - A->parent = iB; + // Swap A and B + B->child1 = iA; + B->parent = A->parent; + A->parent = iB; - // A's old parent should point to B - if (B->parent != b2_nullNode) - { - if (m_nodes[B->parent].child1 == iA) - { - m_nodes[B->parent].child1 = iB; - } - else - { - b2Assert(m_nodes[B->parent].child2 == iA); - m_nodes[B->parent].child2 = iB; - } - } - else - { - m_root = iB; - } + // A's old parent should point to B + if (B->parent != b2_nullNode) + { + if (m_nodes[B->parent].child1 == iA) + { + m_nodes[B->parent].child1 = iB; + } + else + { + b2Assert(m_nodes[B->parent].child2 == iA); + m_nodes[B->parent].child2 = iB; + } + } + else + { + m_root = iB; + } - // Rotate - if (D->height > E->height) - { - B->child2 = iD; - A->child1 = iE; - E->parent = iA; - A->aabb.Combine(C->aabb, E->aabb); - B->aabb.Combine(A->aabb, D->aabb); + // Rotate + if (D->height > E->height) + { + B->child2 = iD; + A->child1 = iE; + E->parent = iA; + A->aabb.Combine(C->aabb, E->aabb); + B->aabb.Combine(A->aabb, D->aabb); - A->height = 1 + b2Max(C->height, E->height); - B->height = 1 + b2Max(A->height, D->height); - } - else - { - B->child2 = iE; - A->child1 = iD; - D->parent = iA; - A->aabb.Combine(C->aabb, D->aabb); - B->aabb.Combine(A->aabb, E->aabb); + A->height = 1 + b2Max(C->height, E->height); + B->height = 1 + b2Max(A->height, D->height); + } + else + { + B->child2 = iE; + A->child1 = iD; + D->parent = iA; + A->aabb.Combine(C->aabb, D->aabb); + B->aabb.Combine(A->aabb, E->aabb); - A->height = 1 + b2Max(C->height, D->height); - B->height = 1 + b2Max(A->height, E->height); - } + A->height = 1 + b2Max(C->height, D->height); + B->height = 1 + b2Max(A->height, E->height); + } - return iB; - } + return iB; + } - return iA; + return iA; } int32 b2DynamicTree::GetHeight() const { - if (m_root == b2_nullNode) - { - return 0; - } + if (m_root == b2_nullNode) + { + return 0; + } - return m_nodes[m_root].height; + return m_nodes[m_root].height; } // float32 b2DynamicTree::GetAreaRatio() const { - if (m_root == b2_nullNode) - { - return 0.0f; - } + if (m_root == b2_nullNode) + { + return 0.0f; + } - const b2TreeNode* root = m_nodes + m_root; - float32 rootArea = root->aabb.GetPerimeter(); + const b2TreeNode* root = m_nodes + m_root; + float32 rootArea = root->aabb.GetPerimeter(); - float32 totalArea = 0.0f; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height < 0) - { - // Free node in pool - continue; - } + float32 totalArea = 0.0f; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height < 0) + { + // Free node in pool + continue; + } - totalArea += node->aabb.GetPerimeter(); - } + totalArea += node->aabb.GetPerimeter(); + } - return totalArea / rootArea; + return totalArea / rootArea; } // Compute the height of a sub-tree. int32 b2DynamicTree::ComputeHeight(int32 nodeId) const { - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2TreeNode* node = m_nodes + nodeId; + b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); + b2TreeNode* node = m_nodes + nodeId; - if (node->IsLeaf()) - { - return 0; - } + if (node->IsLeaf()) + { + return 0; + } - int32 height1 = ComputeHeight(node->child1); - int32 height2 = ComputeHeight(node->child2); - return 1 + b2Max(height1, height2); + int32 height1 = ComputeHeight(node->child1); + int32 height2 = ComputeHeight(node->child2); + return 1 + b2Max(height1, height2); } int32 b2DynamicTree::ComputeHeight() const { - int32 height = ComputeHeight(m_root); - return height; + int32 height = ComputeHeight(m_root); + return height; } void b2DynamicTree::ValidateStructure(int32 index) const { - if (index == b2_nullNode) - { - return; - } + if (index == b2_nullNode) + { + return; + } - if (index == m_root) - { - b2Assert(m_nodes[index].parent == b2_nullNode); - } + if (index == m_root) + { + b2Assert(m_nodes[index].parent == b2_nullNode); + } - const b2TreeNode* node = m_nodes + index; + const b2TreeNode* node = m_nodes + index; - int32 child1 = node->child1; - int32 child2 = node->child2; + int32 child1 = node->child1; + int32 child2 = node->child2; - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); - b2Assert(m_nodes[child1].parent == index); - b2Assert(m_nodes[child2].parent == index); + b2Assert(m_nodes[child1].parent == index); + b2Assert(m_nodes[child2].parent == index); - ValidateStructure(child1); - ValidateStructure(child2); + ValidateStructure(child1); + ValidateStructure(child2); } void b2DynamicTree::ValidateMetrics(int32 index) const { - if (index == b2_nullNode) - { - return; - } + if (index == b2_nullNode) + { + return; + } - const b2TreeNode* node = m_nodes + index; + const b2TreeNode* node = m_nodes + index; - int32 child1 = node->child1; - int32 child2 = node->child2; + int32 child1 = node->child1; + int32 child2 = node->child2; - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } + if (node->IsLeaf()) + { + b2Assert(child1 == b2_nullNode); + b2Assert(child2 == b2_nullNode); + b2Assert(node->height == 0); + return; + } - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); + b2Assert(0 <= child1 && child1 < m_nodeCapacity); + b2Assert(0 <= child2 && child2 < m_nodeCapacity); - int32 height1 = m_nodes[child1].height; - int32 height2 = m_nodes[child2].height; - int32 height; - height = 1 + b2Max(height1, height2); - b2Assert(node->height == height); + int32 height1 = m_nodes[child1].height; + int32 height2 = m_nodes[child2].height; + int32 height; + height = 1 + b2Max(height1, height2); + b2Assert(node->height == height); - b2AABB aabb; - aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); + b2AABB aabb; + aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - b2Assert(aabb.lowerBound == node->aabb.lowerBound); - b2Assert(aabb.upperBound == node->aabb.upperBound); + b2Assert(aabb.lowerBound == node->aabb.lowerBound); + b2Assert(aabb.upperBound == node->aabb.upperBound); - ValidateMetrics(child1); - ValidateMetrics(child2); + ValidateMetrics(child1); + ValidateMetrics(child2); } void b2DynamicTree::Validate() const { - ValidateStructure(m_root); - ValidateMetrics(m_root); + ValidateStructure(m_root); + ValidateMetrics(m_root); - int32 freeCount = 0; - int32 freeIndex = m_freeList; - while (freeIndex != b2_nullNode) - { - b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); - freeIndex = m_nodes[freeIndex].next; - ++freeCount; - } + int32 freeCount = 0; + int32 freeIndex = m_freeList; + while (freeIndex != b2_nullNode) + { + b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); + freeIndex = m_nodes[freeIndex].next; + ++freeCount; + } - b2Assert(GetHeight() == ComputeHeight()); + b2Assert(GetHeight() == ComputeHeight()); - b2Assert(m_nodeCount + freeCount == m_nodeCapacity); + b2Assert(m_nodeCount + freeCount == m_nodeCapacity); } int32 b2DynamicTree::GetMaxBalance() const { - int32 maxBalance = 0; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height <= 1) - { - continue; - } + int32 maxBalance = 0; + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + const b2TreeNode* node = m_nodes + i; + if (node->height <= 1) + { + continue; + } - b2Assert(node->IsLeaf() == false); + b2Assert(node->IsLeaf() == false); - int32 child1 = node->child1; - int32 child2 = node->child2; - int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); - maxBalance = b2Max(maxBalance, balance); - } + int32 child1 = node->child1; + int32 child2 = node->child2; + int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); + maxBalance = b2Max(maxBalance, balance); + } - return maxBalance; + return maxBalance; } void b2DynamicTree::RebuildBottomUp() { - int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); - int32 count = 0; + int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); + int32 count = 0; - // Build array of leaves. Free the rest. - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - if (m_nodes[i].height < 0) - { - // free node in pool - continue; - } + // Build array of leaves. Free the rest. + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + if (m_nodes[i].height < 0) + { + // free node in pool + continue; + } - if (m_nodes[i].IsLeaf()) - { - m_nodes[i].parent = b2_nullNode; - nodes[count] = i; - ++count; - } - else - { - FreeNode(i); - } - } + if (m_nodes[i].IsLeaf()) + { + m_nodes[i].parent = b2_nullNode; + nodes[count] = i; + ++count; + } + else + { + FreeNode(i); + } + } - while (count > 1) - { - float32 minCost = b2_maxFloat; - int32 iMin = -1, jMin = -1; - for (int32 i = 0; i < count; ++i) - { - b2AABB aabbi = m_nodes[nodes[i]].aabb; + while (count > 1) + { + float32 minCost = b2_maxFloat; + int32 iMin = -1, jMin = -1; + for (int32 i = 0; i < count; ++i) + { + b2AABB aabbi = m_nodes[nodes[i]].aabb; - for (int32 j = i + 1; j < count; ++j) - { - b2AABB aabbj = m_nodes[nodes[j]].aabb; - b2AABB b; - b.Combine(aabbi, aabbj); - float32 cost = b.GetPerimeter(); - if (cost < minCost) - { - iMin = i; - jMin = j; - minCost = cost; - } - } - } + for (int32 j = i + 1; j < count; ++j) + { + b2AABB aabbj = m_nodes[nodes[j]].aabb; + b2AABB b; + b.Combine(aabbi, aabbj); + float32 cost = b.GetPerimeter(); + if (cost < minCost) + { + iMin = i; + jMin = j; + minCost = cost; + } + } + } - int32 index1 = nodes[iMin]; - int32 index2 = nodes[jMin]; - b2TreeNode* child1 = m_nodes + index1; - b2TreeNode* child2 = m_nodes + index2; + int32 index1 = nodes[iMin]; + int32 index2 = nodes[jMin]; + b2TreeNode* child1 = m_nodes + index1; + b2TreeNode* child2 = m_nodes + index2; - int32 parentIndex = AllocateNode(); - b2TreeNode* parent = m_nodes + parentIndex; - parent->child1 = index1; - parent->child2 = index2; - parent->height = 1 + b2Max(child1->height, child2->height); - parent->aabb.Combine(child1->aabb, child2->aabb); - parent->parent = b2_nullNode; + int32 parentIndex = AllocateNode(); + b2TreeNode* parent = m_nodes + parentIndex; + parent->child1 = index1; + parent->child2 = index2; + parent->height = 1 + b2Max(child1->height, child2->height); + parent->aabb.Combine(child1->aabb, child2->aabb); + parent->parent = b2_nullNode; - child1->parent = parentIndex; - child2->parent = parentIndex; + child1->parent = parentIndex; + child2->parent = parentIndex; - nodes[jMin] = nodes[count-1]; - nodes[iMin] = parentIndex; - --count; - } + nodes[jMin] = nodes[count-1]; + nodes[iMin] = parentIndex; + --count; + } - m_root = nodes[0]; - b2Free(nodes); + m_root = nodes[0]; + b2Free(nodes); - Validate(); + Validate(); +} + +void b2DynamicTree::ShiftOrigin(const b2Vec2& newOrigin) +{ + // Build array of leaves. Free the rest. + for (int32 i = 0; i < m_nodeCapacity; ++i) + { + m_nodes[i].aabb.lowerBound -= newOrigin; + m_nodes[i].aabb.upperBound -= newOrigin; + } } diff --git a/external/Box2D/Collision/b2DynamicTree.h b/external/Box2D/Collision/b2DynamicTree.h index 33f16b0f32..bf80f73a10 100644 --- a/external/Box2D/Collision/b2DynamicTree.h +++ b/external/Box2D/Collision/b2DynamicTree.h @@ -27,27 +27,27 @@ /// A node in the dynamic tree. The client does not interact with this directly. struct b2TreeNode { - bool IsLeaf() const - { - return child1 == b2_nullNode; - } + bool IsLeaf() const + { + return child1 == b2_nullNode; + } - /// Enlarged AABB - b2AABB aabb; + /// Enlarged AABB + b2AABB aabb; - void* userData; + void* userData; - union - { - int32 parent; - int32 next; - }; + union + { + int32 parent; + int32 next; + }; - int32 child1; - int32 child2; + int32 child1; + int32 child2; - // leaf = 0, free node = -1 - int32 height; + // leaf = 0, free node = -1 + int32 height; }; /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. @@ -61,224 +61,229 @@ struct b2TreeNode class b2DynamicTree { public: - /// Constructing the tree initializes the node pool. - b2DynamicTree(); + /// Constructing the tree initializes the node pool. + b2DynamicTree(); - /// Destroy the tree, freeing the node pool. - ~b2DynamicTree(); + /// Destroy the tree, freeing the node pool. + ~b2DynamicTree(); - /// Create a proxy. Provide a tight fitting AABB and a userData pointer. - int32 CreateProxy(const b2AABB& aabb, void* userData); + /// Create a proxy. Provide a tight fitting AABB and a userData pointer. + int32 CreateProxy(const b2AABB& aabb, void* userData); - /// Destroy a proxy. This asserts if the id is invalid. - void DestroyProxy(int32 proxyId); + /// Destroy a proxy. This asserts if the id is invalid. + void DestroyProxy(int32 proxyId); - /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, - /// then the proxy is removed from the tree and re-inserted. Otherwise - /// the function returns immediately. - /// @return true if the proxy was re-inserted. - bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); + /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, + /// then the proxy is removed from the tree and re-inserted. Otherwise + /// the function returns immediately. + /// @return true if the proxy was re-inserted. + bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); - /// Get proxy user data. - /// @return the proxy user data or 0 if the id is invalid. - void* GetUserData(int32 proxyId) const; + /// Get proxy user data. + /// @return the proxy user data or 0 if the id is invalid. + void* GetUserData(int32 proxyId) const; - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; + /// Get the fat AABB for a proxy. + const b2AABB& GetFatAABB(int32 proxyId) const; - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template - void Query(T* callback, const b2AABB& aabb) const; + /// Query an AABB for overlapping proxies. The callback class + /// is called for each proxy that overlaps the supplied AABB. + template + void Query(T* callback, const b2AABB& aabb) const; - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template - void RayCast(T* callback, const b2RayCastInput& input) const; + /// Ray-cast against the proxies in the tree. This relies on the callback + /// to perform a exact ray-cast in the case were the proxy contains a shape. + /// The callback also performs the any collision filtering. This has performance + /// roughly equal to k * log(n), where k is the number of collisions and n is the + /// number of proxies in the tree. + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. + template + void RayCast(T* callback, const b2RayCastInput& input) const; - /// Validate this tree. For testing. - void Validate() const; + /// Validate this tree. For testing. + void Validate() const; - /// Compute the height of the binary tree in O(N) time. Should not be - /// called often. - int32 GetHeight() const; + /// Compute the height of the binary tree in O(N) time. Should not be + /// called often. + int32 GetHeight() const; - /// Get the maximum balance of an node in the tree. The balance is the difference - /// in height of the two children of a node. - int32 GetMaxBalance() const; + /// Get the maximum balance of an node in the tree. The balance is the difference + /// in height of the two children of a node. + int32 GetMaxBalance() const; - /// Get the ratio of the sum of the node areas to the root area. - float32 GetAreaRatio() const; + /// Get the ratio of the sum of the node areas to the root area. + float32 GetAreaRatio() const; - /// Build an optimal tree. Very expensive. For testing. - void RebuildBottomUp(); + /// Build an optimal tree. Very expensive. For testing. + void RebuildBottomUp(); + + /// Shift the world origin. Useful for large worlds. + /// The shift formula is: position -= newOrigin + /// @param newOrigin the new origin with respect to the old origin + void ShiftOrigin(const b2Vec2& newOrigin); private: - int32 AllocateNode(); - void FreeNode(int32 node); + int32 AllocateNode(); + void FreeNode(int32 node); - void InsertLeaf(int32 node); - void RemoveLeaf(int32 node); + void InsertLeaf(int32 node); + void RemoveLeaf(int32 node); - int32 Balance(int32 index); + int32 Balance(int32 index); - int32 ComputeHeight() const; - int32 ComputeHeight(int32 nodeId) const; + int32 ComputeHeight() const; + int32 ComputeHeight(int32 nodeId) const; - void ValidateStructure(int32 index) const; - void ValidateMetrics(int32 index) const; + void ValidateStructure(int32 index) const; + void ValidateMetrics(int32 index) const; - int32 m_root; + int32 m_root; - b2TreeNode* m_nodes; - int32 m_nodeCount; - int32 m_nodeCapacity; + b2TreeNode* m_nodes; + int32 m_nodeCount; + int32 m_nodeCapacity; - int32 m_freeList; + int32 m_freeList; - /// This is used to incrementally traverse the tree for re-balancing. - uint32 m_path; + /// This is used to incrementally traverse the tree for re-balancing. + uint32 m_path; - int32 m_insertionCount; + int32 m_insertionCount; }; inline void* b2DynamicTree::GetUserData(int32 proxyId) const { - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].userData; + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].userData; } inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const { - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].aabb; + b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); + return m_nodes[proxyId].aabb; } template inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const { - b2GrowableStack stack; - stack.Push(m_root); + b2GrowableStack stack; + stack.Push(m_root); - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } - const b2TreeNode* node = m_nodes + nodeId; + const b2TreeNode* node = m_nodes + nodeId; - if (b2TestOverlap(node->aabb, aabb)) - { - if (node->IsLeaf()) - { - bool proceed = callback->QueryCallback(nodeId); - if (proceed == false) - { - return; - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } - } + if (b2TestOverlap(node->aabb, aabb)) + { + if (node->IsLeaf()) + { + bool proceed = callback->QueryCallback(nodeId); + if (proceed == false) + { + return; + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } + } } template inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const { - b2Vec2 p1 = input.p1; - b2Vec2 p2 = input.p2; - b2Vec2 r = p2 - p1; - b2Assert(r.LengthSquared() > 0.0f); - r.Normalize(); + b2Vec2 p1 = input.p1; + b2Vec2 p2 = input.p2; + b2Vec2 r = p2 - p1; + b2Assert(r.LengthSquared() > 0.0f); + r.Normalize(); - // v is perpendicular to the segment. - b2Vec2 v = b2Cross(1.0f, r); - b2Vec2 abs_v = b2Abs(v); + // v is perpendicular to the segment. + b2Vec2 v = b2Cross(1.0f, r); + b2Vec2 abs_v = b2Abs(v); - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) - float32 maxFraction = input.maxFraction; + float32 maxFraction = input.maxFraction; - // Build a bounding box for the segment. - b2AABB segmentAABB; - { - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } + // Build a bounding box for the segment. + b2AABB segmentAABB; + { + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } - b2GrowableStack stack; - stack.Push(m_root); + b2GrowableStack stack; + stack.Push(m_root); - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } + while (stack.GetCount() > 0) + { + int32 nodeId = stack.Pop(); + if (nodeId == b2_nullNode) + { + continue; + } - const b2TreeNode* node = m_nodes + nodeId; + const b2TreeNode* node = m_nodes + nodeId; - if (b2TestOverlap(node->aabb, segmentAABB) == false) - { - continue; - } + if (b2TestOverlap(node->aabb, segmentAABB) == false) + { + continue; + } - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - b2Vec2 c = node->aabb.GetCenter(); - b2Vec2 h = node->aabb.GetExtents(); - float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); - if (separation > 0.0f) - { - continue; - } + // Separating axis for segment (Gino, p80). + // |dot(v, p1 - c)| > dot(|v|, h) + b2Vec2 c = node->aabb.GetCenter(); + b2Vec2 h = node->aabb.GetExtents(); + float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); + if (separation > 0.0f) + { + continue; + } - if (node->IsLeaf()) - { - b2RayCastInput subInput; - subInput.p1 = input.p1; - subInput.p2 = input.p2; - subInput.maxFraction = maxFraction; + if (node->IsLeaf()) + { + b2RayCastInput subInput; + subInput.p1 = input.p1; + subInput.p2 = input.p2; + subInput.maxFraction = maxFraction; - float32 value = callback->RayCastCallback(subInput, nodeId); + float32 value = callback->RayCastCallback(subInput, nodeId); - if (value == 0.0f) - { - // The client has terminated the ray cast. - return; - } + if (value == 0.0f) + { + // The client has terminated the ray cast. + return; + } - if (value > 0.0f) - { - // Update segment bounding box. - maxFraction = value; - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } + if (value > 0.0f) + { + // Update segment bounding box. + maxFraction = value; + b2Vec2 t = p1 + maxFraction * (p2 - p1); + segmentAABB.lowerBound = b2Min(p1, t); + segmentAABB.upperBound = b2Max(p1, t); + } + } + else + { + stack.Push(node->child1); + stack.Push(node->child2); + } + } } #endif diff --git a/external/Box2D/Collision/b2TimeOfImpact.cpp b/external/Box2D/Collision/b2TimeOfImpact.cpp index 1d643addd8..60da95c389 100644 --- a/external/Box2D/Collision/b2TimeOfImpact.cpp +++ b/external/Box2D/Collision/b2TimeOfImpact.cpp @@ -21,468 +21,466 @@ #include #include #include +#include -#ifdef SHP #include -#else -#include -#endif - -using namespace std; +float32 b2_toiTime, b2_toiMaxTime; int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; int32 b2_toiRootIters, b2_toiMaxRootIters; +// struct b2SeparationFunction { - enum Type - { - e_points, - e_faceA, - e_faceB - }; + enum Type + { + e_points, + e_faceA, + e_faceB + }; - // TODO_ERIN might not need to return the separation + // TODO_ERIN might not need to return the separation - float32 Initialize(const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Sweep& sweepA, - const b2DistanceProxy* proxyB, const b2Sweep& sweepB, - float32 t1) - { - m_proxyA = proxyA; - m_proxyB = proxyB; - int32 count = cache->count; - b2Assert(0 < count && count < 3); + float32 Initialize(const b2SimplexCache* cache, + const b2DistanceProxy* proxyA, const b2Sweep& sweepA, + const b2DistanceProxy* proxyB, const b2Sweep& sweepB, + float32 t1) + { + m_proxyA = proxyA; + m_proxyB = proxyB; + int32 count = cache->count; + b2Assert(0 < count && count < 3); - m_sweepA = sweepA; - m_sweepB = sweepB; + m_sweepA = sweepA; + m_sweepB = sweepB; - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t1); - m_sweepB.GetTransform(&xfB, t1); + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t1); + m_sweepB.GetTransform(&xfB, t1); - if (count == 1) - { - m_type = e_points; - b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - m_axis = pointB - pointA; - float32 s = m_axis.Normalize(); - return s; - } - else if (cache->indexA[0] == cache->indexA[1]) - { - // Two points on B and one on A. - m_type = e_faceB; - b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); - b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); + if (count == 1) + { + m_type = e_points; + b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + m_axis = pointB - pointA; + float32 s = m_axis.Normalize(); + return s; + } + else if (cache->indexA[0] == cache->indexA[1]) + { + // Two points on B and one on A. + m_type = e_faceB; + b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); + b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); - m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfB.q, m_axis); + m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfB.q, m_axis); - m_localPoint = 0.5f * (localPointB1 + localPointB2); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); + m_localPoint = 0.5f * (localPointB1 + localPointB2); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); - b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); + b2Vec2 pointA = b2Mul(xfA, localPointA); - float32 s = b2Dot(pointA - pointB, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - else - { - // Two points on A and one or two points on B. - m_type = e_faceA; - b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); - - m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfA.q, m_axis); + float32 s = b2Dot(pointA - pointB, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + else + { + // Two points on A and one or two points on B. + m_type = e_faceA; + b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); + b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); + + m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); + m_axis.Normalize(); + b2Vec2 normal = b2Mul(xfA.q, m_axis); - m_localPoint = 0.5f * (localPointA1 + localPointA2); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); + m_localPoint = 0.5f * (localPointA1 + localPointA2); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointB = b2Mul(xfB, localPointB); + b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); + b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 s = b2Dot(pointB - pointA, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - } + float32 s = b2Dot(pointB - pointA, normal); + if (s < 0.0f) + { + m_axis = -m_axis; + s = -s; + } + return s; + } + } - float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); + // + float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + switch (m_type) + { + case e_points: + { + b2Vec2 axisA = b2MulT(xfA.q, m_axis); + b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - *indexA = m_proxyA->GetSupport(axisA); - *indexB = m_proxyB->GetSupport(axisB); + *indexA = m_proxyA->GetSupport(axisA); + *indexB = m_proxyB->GetSupport(axisB); - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, m_axis); - return separation; - } + float32 separation = b2Dot(pointB - pointA, m_axis); + return separation; + } - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - *indexA = -1; - *indexB = m_proxyB->GetSupport(axisB); + b2Vec2 axisB = b2MulT(xfB.q, -normal); + + *indexA = -1; + *indexB = m_proxyB->GetSupport(axisB); - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); + b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); - b2Vec2 axisA = b2MulT(xfA.q, -normal); + b2Vec2 axisA = b2MulT(xfA.q, -normal); - *indexB = -1; - *indexA = m_proxyA->GetSupport(axisA); + *indexB = -1; + *indexA = m_proxyA->GetSupport(axisA); - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } - default: - b2Assert(false); - *indexA = -1; - *indexB = -1; - return 0.0f; - } - } + default: + b2Assert(false); + *indexA = -1; + *indexB = -1; + return 0.0f; + } + } - float32 Evaluate(int32 indexA, int32 indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); + // + float32 Evaluate(int32 indexA, int32 indexB, float32 t) const + { + b2Transform xfA, xfB; + m_sweepA.GetTransform(&xfA, t); + m_sweepB.GetTransform(&xfB, t); - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); + switch (m_type) + { + case e_points: + { + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + b2Vec2 pointA = b2Mul(xfA, localPointA); + b2Vec2 pointB = b2Mul(xfB, localPointB); + float32 separation = b2Dot(pointB - pointA, m_axis); - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, m_axis); + return separation; + } - return separation; - } + case e_faceA: + { + b2Vec2 normal = b2Mul(xfA.q, m_axis); + b2Vec2 pointA = b2Mul(xfA, m_localPoint); - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); + b2Vec2 localPointB = m_proxyB->GetVertex(indexB); + b2Vec2 pointB = b2Mul(xfB, localPointB); - b2Vec2 axisB = b2MulT(xfB.q, -normal); + float32 separation = b2Dot(pointB - pointA, normal); + return separation; + } - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); + case e_faceB: + { + b2Vec2 normal = b2Mul(xfB.q, m_axis); + b2Vec2 pointB = b2Mul(xfB, m_localPoint); - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } + b2Vec2 localPointA = m_proxyA->GetVertex(indexA); + b2Vec2 pointA = b2Mul(xfA, localPointA); - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); + float32 separation = b2Dot(pointA - pointB, normal); + return separation; + } - b2Vec2 axisA = b2MulT(xfA.q, -normal); + default: + b2Assert(false); + return 0.0f; + } + } - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - return 0.0f; - } - } - - const b2DistanceProxy* m_proxyA; - const b2DistanceProxy* m_proxyB; - b2Sweep m_sweepA, m_sweepB; - Type m_type; - b2Vec2 m_localPoint; - b2Vec2 m_axis; + const b2DistanceProxy* m_proxyA; + const b2DistanceProxy* m_proxyB; + b2Sweep m_sweepA, m_sweepB; + Type m_type; + b2Vec2 m_localPoint; + b2Vec2 m_axis; }; // CCD via the local separating axis method. This seeks progression // by computing the largest time at which separation is maintained. void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) { - ++b2_toiCalls; + b2Timer timer; - output->state = b2TOIOutput::e_unknown; - output->t = input->tMax; + ++b2_toiCalls; - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; + output->state = b2TOIOutput::e_unknown; + output->t = input->tMax; - b2Sweep sweepA = input->sweepA; - b2Sweep sweepB = input->sweepB; + const b2DistanceProxy* proxyA = &input->proxyA; + const b2DistanceProxy* proxyB = &input->proxyB; - // Large rotations can make the root finder fail, so we normalize the - // sweep angles. - sweepA.Normalize(); - sweepB.Normalize(); + b2Sweep sweepA = input->sweepA; + b2Sweep sweepB = input->sweepB; - float32 tMax = input->tMax; + // Large rotations can make the root finder fail, so we normalize the + // sweep angles. + sweepA.Normalize(); + sweepB.Normalize(); - float32 totalRadius = proxyA->m_radius + proxyB->m_radius; - float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); - float32 tolerance = 0.25f * b2_linearSlop; - b2Assert(target > tolerance); + float32 tMax = input->tMax; - float32 t1 = 0.0f; - const int32 k_maxIterations = 20; // TODO_ERIN b2Settings - int32 iter = 0; + float32 totalRadius = proxyA->m_radius + proxyB->m_radius; + float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); + float32 tolerance = 0.25f * b2_linearSlop; + b2Assert(target > tolerance); - // Prepare input for distance query. - b2SimplexCache cache; - cache.count = 0; - b2DistanceInput distanceInput; - distanceInput.proxyA = input->proxyA; - distanceInput.proxyB = input->proxyB; - distanceInput.useRadii = false; + float32 t1 = 0.0f; + const int32 k_maxIterations = 20; // TODO_ERIN b2Settings + int32 iter = 0; - // The outer loop progressively attempts to compute new separating axes. - // This loop terminates when an axis is repeated (no progress is made). - for(;;) - { - b2Transform xfA, xfB; - sweepA.GetTransform(&xfA, t1); - sweepB.GetTransform(&xfB, t1); + // Prepare input for distance query. + b2SimplexCache cache; + cache.count = 0; + b2DistanceInput distanceInput; + distanceInput.proxyA = input->proxyA; + distanceInput.proxyB = input->proxyB; + distanceInput.useRadii = false; - // Get the distance between shapes. We can also use the results - // to get a separating axis. - distanceInput.transformA = xfA; - distanceInput.transformB = xfB; - b2DistanceOutput distanceOutput; - b2Distance(&distanceOutput, &cache, &distanceInput); + // The outer loop progressively attempts to compute new separating axes. + // This loop terminates when an axis is repeated (no progress is made). + for(;;) + { + b2Transform xfA, xfB; + sweepA.GetTransform(&xfA, t1); + sweepB.GetTransform(&xfB, t1); - // If the shapes are overlapped, we give up on continuous collision. - if (distanceOutput.distance <= 0.0f) - { - // Failure! - output->state = b2TOIOutput::e_overlapped; - output->t = 0.0f; - break; - } + // Get the distance between shapes. We can also use the results + // to get a separating axis. + distanceInput.transformA = xfA; + distanceInput.transformB = xfB; + b2DistanceOutput distanceOutput; + b2Distance(&distanceOutput, &cache, &distanceInput); - if (distanceOutput.distance < target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_touching; - output->t = t1; - break; - } + // If the shapes are overlapped, we give up on continuous collision. + if (distanceOutput.distance <= 0.0f) + { + // Failure! + output->state = b2TOIOutput::e_overlapped; + output->t = 0.0f; + break; + } - // Initialize the separating axis. - b2SeparationFunction fcn; - fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); + if (distanceOutput.distance < target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_touching; + output->t = t1; + break; + } + + // Initialize the separating axis. + b2SeparationFunction fcn; + fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); #if 0 - // Dump the curve seen by the root finder - { - const int32 N = 100; - float32 dx = 1.0f / N; - float32 xs[N+1]; - float32 fs[N+1]; + // Dump the curve seen by the root finder + { + const int32 N = 100; + float32 dx = 1.0f / N; + float32 xs[N+1]; + float32 fs[N+1]; - float32 x = 0.0f; + float32 x = 0.0f; - for (int32 i = 0; i <= N; ++i) - { - sweepA.GetTransform(&xfA, x); - sweepB.GetTransform(&xfB, x); - float32 f = fcn.Evaluate(xfA, xfB) - target; + for (int32 i = 0; i <= N; ++i) + { + sweepA.GetTransform(&xfA, x); + sweepB.GetTransform(&xfB, x); + float32 f = fcn.Evaluate(xfA, xfB) - target; - printf("%g %g\n", x, f); + printf("%g %g\n", x, f); - xs[i] = x; - fs[i] = f; + xs[i] = x; + fs[i] = f; - x += dx; - } - } + x += dx; + } + } #endif - // Compute the TOI on the separating axis. We do this by successively - // resolving the deepest point. This loop is bounded by the number of vertices. - bool done = false; - float32 t2 = tMax; - int32 pushBackIter = 0; - for (;;) - { - // Find the deepest point at t2. Store the witness point indices. - int32 indexA, indexB; - float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); + // Compute the TOI on the separating axis. We do this by successively + // resolving the deepest point. This loop is bounded by the number of vertices. + bool done = false; + float32 t2 = tMax; + int32 pushBackIter = 0; + for (;;) + { + // Find the deepest point at t2. Store the witness point indices. + int32 indexA, indexB; + float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); - // Is the final configuration separated? - if (s2 > target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_separated; - output->t = tMax; - done = true; - break; - } + // Is the final configuration separated? + if (s2 > target + tolerance) + { + // Victory! + output->state = b2TOIOutput::e_separated; + output->t = tMax; + done = true; + break; + } - // Has the separation reached tolerance? - if (s2 > target - tolerance) - { - // Advance the sweeps - t1 = t2; - break; - } + // Has the separation reached tolerance? + if (s2 > target - tolerance) + { + // Advance the sweeps + t1 = t2; + break; + } - // Compute the initial separation of the witness points. - float32 s1 = fcn.Evaluate(indexA, indexB, t1); + // Compute the initial separation of the witness points. + float32 s1 = fcn.Evaluate(indexA, indexB, t1); - // Check for initial overlap. This might happen if the root finder - // runs out of iterations. - if (s1 < target - tolerance) - { - output->state = b2TOIOutput::e_failed; - output->t = t1; - done = true; - break; - } + // Check for initial overlap. This might happen if the root finder + // runs out of iterations. + if (s1 < target - tolerance) + { + output->state = b2TOIOutput::e_failed; + output->t = t1; + done = true; + break; + } - // Check for touching - if (s1 <= target + tolerance) - { - // Victory! t1 should hold the TOI (could be 0.0). - output->state = b2TOIOutput::e_touching; - output->t = t1; - done = true; - break; - } + // Check for touching + if (s1 <= target + tolerance) + { + // Victory! t1 should hold the TOI (could be 0.0). + output->state = b2TOIOutput::e_touching; + output->t = t1; + done = true; + break; + } - // Compute 1D root of: f(x) - target = 0 - int32 rootIterCount = 0; - float32 a1 = t1, a2 = t2; - for (;;) - { - // Use a mix of the secant rule and bisection. - float32 t; - if (rootIterCount & 1) - { - // Secant rule to improve convergence. - t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); - } - else - { - // Bisection to guarantee progress. - t = 0.5f * (a1 + a2); - } + // Compute 1D root of: f(x) - target = 0 + int32 rootIterCount = 0; + float32 a1 = t1, a2 = t2; + for (;;) + { + // Use a mix of the secant rule and bisection. + float32 t; + if (rootIterCount & 1) + { + // Secant rule to improve convergence. + t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); + } + else + { + // Bisection to guarantee progress. + t = 0.5f * (a1 + a2); + } - float32 s = fcn.Evaluate(indexA, indexB, t); + ++rootIterCount; + ++b2_toiRootIters; - if (b2Abs(s - target) < tolerance) - { - // t2 holds a tentative value for t1 - t2 = t; - break; - } + float32 s = fcn.Evaluate(indexA, indexB, t); - // Ensure we continue to bracket the root. - if (s > target) - { - a1 = t; - s1 = s; - } - else - { - a2 = t; - s2 = s; - } + if (b2Abs(s - target) < tolerance) + { + // t2 holds a tentative value for t1 + t2 = t; + break; + } - ++rootIterCount; - ++b2_toiRootIters; + // Ensure we continue to bracket the root. + if (s > target) + { + a1 = t; + s1 = s; + } + else + { + a2 = t; + s2 = s; + } + + if (rootIterCount == 50) + { + break; + } + } - if (rootIterCount == 50) - { - break; - } - } + b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); - b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); + ++pushBackIter; - ++pushBackIter; + if (pushBackIter == b2_maxPolygonVertices) + { + break; + } + } - if (pushBackIter == b2_maxPolygonVertices) - { - break; - } - } + ++iter; + ++b2_toiIters; - ++iter; - ++b2_toiIters; + if (done) + { + break; + } - if (done) - { - break; - } + if (iter == k_maxIterations) + { + // Root finder got stuck. Semi-victory. + output->state = b2TOIOutput::e_failed; + output->t = t1; + break; + } + } - if (iter == k_maxIterations) - { - // Root finder got stuck. Semi-victory. - output->state = b2TOIOutput::e_failed; - output->t = t1; - break; - } - } + b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); - b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); + float32 time = timer.GetMilliseconds(); + b2_toiMaxTime = b2Max(b2_toiMaxTime, time); + b2_toiTime += time; } diff --git a/external/Box2D/Collision/b2TimeOfImpact.h b/external/Box2D/Collision/b2TimeOfImpact.h index 2e4f8228ff..20620c1ee7 100644 --- a/external/Box2D/Collision/b2TimeOfImpact.h +++ b/external/Box2D/Collision/b2TimeOfImpact.h @@ -25,27 +25,27 @@ /// Input parameters for b2TimeOfImpact struct b2TOIInput { - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Sweep sweepA; - b2Sweep sweepB; - float32 tMax; // defines sweep interval [0, tMax] + b2DistanceProxy proxyA; + b2DistanceProxy proxyB; + b2Sweep sweepA; + b2Sweep sweepB; + float32 tMax; // defines sweep interval [0, tMax] }; // Output parameters for b2TimeOfImpact. struct b2TOIOutput { - enum State - { - e_unknown, - e_failed, - e_overlapped, - e_touching, - e_separated - }; + enum State + { + e_unknown, + e_failed, + e_overlapped, + e_touching, + e_separated + }; - State state; - float32 t; + State state; + float32 t; }; /// Compute the upper bound on time before two shapes penetrate. Time is represented as diff --git a/external/Box2D/Common/b2BlockAllocator.cpp b/external/Box2D/Common/b2BlockAllocator.cpp index 2e862091f9..f7a4688ea9 100644 --- a/external/Box2D/Common/b2BlockAllocator.cpp +++ b/external/Box2D/Common/b2BlockAllocator.cpp @@ -17,202 +17,199 @@ */ #include -#include -#include -#include -#include - -using namespace std; +#include +#include +#include int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = { - 16, // 0 - 32, // 1 - 64, // 2 - 96, // 3 - 128, // 4 - 160, // 5 - 192, // 6 - 224, // 7 - 256, // 8 - 320, // 9 - 384, // 10 - 448, // 11 - 512, // 12 - 640, // 13 + 16, // 0 + 32, // 1 + 64, // 2 + 96, // 3 + 128, // 4 + 160, // 5 + 192, // 6 + 224, // 7 + 256, // 8 + 320, // 9 + 384, // 10 + 448, // 11 + 512, // 12 + 640, // 13 }; uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; bool b2BlockAllocator::s_blockSizeLookupInitialized; struct b2Chunk { - int32 blockSize; - b2Block* blocks; + int32 blockSize; + b2Block* blocks; }; struct b2Block { - b2Block* next; + b2Block* next; }; b2BlockAllocator::b2BlockAllocator() { - b2Assert(b2_blockSizes < UCHAR_MAX); + b2Assert(b2_blockSizes < UCHAR_MAX); - m_chunkSpace = b2_chunkArrayIncrement; - m_chunkCount = 0; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - memset(m_freeLists, 0, sizeof(m_freeLists)); + m_chunkSpace = b2_chunkArrayIncrement; + m_chunkCount = 0; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + memset(m_freeLists, 0, sizeof(m_freeLists)); - if (s_blockSizeLookupInitialized == false) - { - int32 j = 0; - for (int32 i = 1; i <= b2_maxBlockSize; ++i) - { - b2Assert(j < b2_blockSizes); - if (i <= s_blockSizes[j]) - { - s_blockSizeLookup[i] = (uint8)j; - } - else - { - ++j; - s_blockSizeLookup[i] = (uint8)j; - } - } + if (s_blockSizeLookupInitialized == false) + { + int32 j = 0; + for (int32 i = 1; i <= b2_maxBlockSize; ++i) + { + b2Assert(j < b2_blockSizes); + if (i <= s_blockSizes[j]) + { + s_blockSizeLookup[i] = (uint8)j; + } + else + { + ++j; + s_blockSizeLookup[i] = (uint8)j; + } + } - s_blockSizeLookupInitialized = true; - } + s_blockSizeLookupInitialized = true; + } } b2BlockAllocator::~b2BlockAllocator() { - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } - b2Free(m_chunks); + b2Free(m_chunks); } void* b2BlockAllocator::Allocate(int32 size) { - if (size == 0) - return NULL; + if (size == 0) + return NULL; - b2Assert(0 < size); + b2Assert(0 < size); - if (size > b2_maxBlockSize) - { - return b2Alloc(size); - } + if (size > b2_maxBlockSize) + { + return b2Alloc(size); + } - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); - if (m_freeLists[index]) - { - b2Block* block = m_freeLists[index]; - m_freeLists[index] = block->next; - return block; - } - else - { - if (m_chunkCount == m_chunkSpace) - { - b2Chunk* oldChunks = m_chunks; - m_chunkSpace += b2_chunkArrayIncrement; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); - memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); - b2Free(oldChunks); - } + if (m_freeLists[index]) + { + b2Block* block = m_freeLists[index]; + m_freeLists[index] = block->next; + return block; + } + else + { + if (m_chunkCount == m_chunkSpace) + { + b2Chunk* oldChunks = m_chunks; + m_chunkSpace += b2_chunkArrayIncrement; + m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); + memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); + memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); + b2Free(oldChunks); + } - b2Chunk* chunk = m_chunks + m_chunkCount; - chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); + b2Chunk* chunk = m_chunks + m_chunkCount; + chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); #if defined(_DEBUG) - memset(chunk->blocks, 0xcd, b2_chunkSize); + memset(chunk->blocks, 0xcd, b2_chunkSize); #endif - int32 blockSize = s_blockSizes[index]; - chunk->blockSize = blockSize; - int32 blockCount = b2_chunkSize / blockSize; - b2Assert(blockCount * blockSize <= b2_chunkSize); - for (int32 i = 0; i < blockCount - 1; ++i) - { - b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); - b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); - block->next = next; - } - b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); - last->next = NULL; + int32 blockSize = s_blockSizes[index]; + chunk->blockSize = blockSize; + int32 blockCount = b2_chunkSize / blockSize; + b2Assert(blockCount * blockSize <= b2_chunkSize); + for (int32 i = 0; i < blockCount - 1; ++i) + { + b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); + b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); + block->next = next; + } + b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); + last->next = NULL; - m_freeLists[index] = chunk->blocks->next; - ++m_chunkCount; + m_freeLists[index] = chunk->blocks->next; + ++m_chunkCount; - return chunk->blocks; - } + return chunk->blocks; + } } void b2BlockAllocator::Free(void* p, int32 size) { - if (size == 0) - { - return; - } + if (size == 0) + { + return; + } - b2Assert(0 < size); + b2Assert(0 < size); - if (size > b2_maxBlockSize) - { - b2Free(p); - return; - } + if (size > b2_maxBlockSize) + { + b2Free(p); + return; + } - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); + int32 index = s_blockSizeLookup[size]; + b2Assert(0 <= index && index < b2_blockSizes); #ifdef _DEBUG - // Verify the memory address and size is valid. - int32 blockSize = s_blockSizes[index]; - bool found = false; - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Chunk* chunk = m_chunks + i; - if (chunk->blockSize != blockSize) - { - b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || - (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); - } - else - { - if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) - { - found = true; - } - } - } + // Verify the memory address and size is valid. + int32 blockSize = s_blockSizes[index]; + bool found = false; + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Chunk* chunk = m_chunks + i; + if (chunk->blockSize != blockSize) + { + b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || + (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); + } + else + { + if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) + { + found = true; + } + } + } - b2Assert(found); + b2Assert(found); - memset(p, 0xfd, blockSize); + memset(p, 0xfd, blockSize); #endif - b2Block* block = (b2Block*)p; - block->next = m_freeLists[index]; - m_freeLists[index] = block; + b2Block* block = (b2Block*)p; + block->next = m_freeLists[index]; + m_freeLists[index] = block; } void b2BlockAllocator::Clear() { - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } + for (int32 i = 0; i < m_chunkCount; ++i) + { + b2Free(m_chunks[i].blocks); + } - m_chunkCount = 0; - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); + m_chunkCount = 0; + memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - memset(m_freeLists, 0, sizeof(m_freeLists)); + memset(m_freeLists, 0, sizeof(m_freeLists)); } diff --git a/external/Box2D/Common/b2BlockAllocator.h b/external/Box2D/Common/b2BlockAllocator.h index ec221fdf61..cea3cef968 100644 --- a/external/Box2D/Common/b2BlockAllocator.h +++ b/external/Box2D/Common/b2BlockAllocator.h @@ -35,28 +35,28 @@ struct b2Chunk; class b2BlockAllocator { public: - b2BlockAllocator(); - ~b2BlockAllocator(); + b2BlockAllocator(); + ~b2BlockAllocator(); - /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. - void* Allocate(int32 size); + /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. + void* Allocate(int32 size); - /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. - void Free(void* p, int32 size); + /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. + void Free(void* p, int32 size); - void Clear(); + void Clear(); private: - b2Chunk* m_chunks; - int32 m_chunkCount; - int32 m_chunkSpace; + b2Chunk* m_chunks; + int32 m_chunkCount; + int32 m_chunkSpace; - b2Block* m_freeLists[b2_blockSizes]; + b2Block* m_freeLists[b2_blockSizes]; - static int32 s_blockSizes[b2_blockSizes]; - static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; - static bool s_blockSizeLookupInitialized; + static int32 s_blockSizes[b2_blockSizes]; + static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; + static bool s_blockSizeLookupInitialized; }; #endif diff --git a/external/Box2D/Common/b2Draw.cpp b/external/Box2D/Common/b2Draw.cpp index cb760025e9..2cd9b1a568 100644 --- a/external/Box2D/Common/b2Draw.cpp +++ b/external/Box2D/Common/b2Draw.cpp @@ -20,25 +20,25 @@ b2Draw::b2Draw() { - m_drawFlags = 0; + m_drawFlags = 0; } void b2Draw::SetFlags(uint32 flags) { - m_drawFlags = flags; + m_drawFlags = flags; } uint32 b2Draw::GetFlags() const { - return m_drawFlags; + return m_drawFlags; } void b2Draw::AppendFlags(uint32 flags) { - m_drawFlags |= flags; + m_drawFlags |= flags; } void b2Draw::ClearFlags(uint32 flags) { - m_drawFlags &= ~flags; + m_drawFlags &= ~flags; } diff --git a/external/Box2D/Common/b2Draw.h b/external/Box2D/Common/b2Draw.h index b33cd8d38f..20359c913d 100644 --- a/external/Box2D/Common/b2Draw.h +++ b/external/Box2D/Common/b2Draw.h @@ -16,15 +16,18 @@ * 3. This notice may not be removed or altered from any source distribution. */ +#ifndef B2_DRAW_H +#define B2_DRAW_H + #include /// Color for debug drawing. Each value has the range [0,1]. struct b2Color { - b2Color() {} - b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} - void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } - float32 r, g, b; + b2Color() {} + b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} + void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } + float32 r, g, b; }; /// Implement and register this class with a b2World to provide debug drawing of physics @@ -32,50 +35,52 @@ struct b2Color class b2Draw { public: - b2Draw(); + b2Draw(); - virtual ~b2Draw() {} + virtual ~b2Draw() {} - enum - { - e_shapeBit = 0x0001, ///< draw shapes - e_jointBit = 0x0002, ///< draw joint connections - e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes - e_pairBit = 0x0008, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0010 ///< draw center of mass frame - }; + enum + { + e_shapeBit = 0x0001, ///< draw shapes + e_jointBit = 0x0002, ///< draw joint connections + e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes + e_pairBit = 0x0008, ///< draw broad-phase pairs + e_centerOfMassBit = 0x0010 ///< draw center of mass frame + }; - /// Set the drawing flags. - void SetFlags(uint32 flags); + /// Set the drawing flags. + void SetFlags(uint32 flags); - /// Get the drawing flags. - uint32 GetFlags() const; - - /// Append flags to the current flags. - void AppendFlags(uint32 flags); + /// Get the drawing flags. + uint32 GetFlags() const; + + /// Append flags to the current flags. + void AppendFlags(uint32 flags); - /// Clear flags from the current flags. - void ClearFlags(uint32 flags); + /// Clear flags from the current flags. + void ClearFlags(uint32 flags); - /// Draw a closed polygon provided in CCW order. - virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + /// Draw a closed polygon provided in CCW order. + virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - /// Draw a solid closed polygon provided in CCW order. - virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; + /// Draw a solid closed polygon provided in CCW order. + virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - /// Draw a circle. - virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; - - /// Draw a solid circle. - virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; - - /// Draw a line segment. - virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; + /// Draw a circle. + virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; + + /// Draw a solid circle. + virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; + + /// Draw a line segment. + virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; - /// Draw a transform. Choose your own length scale. - /// @param xf a transform. - virtual void DrawTransform(const b2Transform& xf) = 0; + /// Draw a transform. Choose your own length scale. + /// @param xf a transform. + virtual void DrawTransform(const b2Transform& xf) = 0; protected: - uint32 m_drawFlags; + uint32 m_drawFlags; }; + +#endif diff --git a/external/Box2D/Common/b2GrowableStack.h b/external/Box2D/Common/b2GrowableStack.h index 68809521f4..4094644a28 100644 --- a/external/Box2D/Common/b2GrowableStack.h +++ b/external/Box2D/Common/b2GrowableStack.h @@ -19,7 +19,7 @@ #ifndef B2_GROWABLE_STACK_H #define B2_GROWABLE_STACK_H #include -#include +#include /// This is a growable LIFO stack with an initial capacity of N. /// If the stack size exceeds the initial capacity, the heap is used @@ -28,57 +28,57 @@ template class b2GrowableStack { public: - b2GrowableStack() - { - m_stack = m_array; - m_count = 0; - m_capacity = N; - } + b2GrowableStack() + { + m_stack = m_array; + m_count = 0; + m_capacity = N; + } - ~b2GrowableStack() - { - if (m_stack != m_array) - { - b2Free(m_stack); - m_stack = NULL; - } - } + ~b2GrowableStack() + { + if (m_stack != m_array) + { + b2Free(m_stack); + m_stack = NULL; + } + } - void Push(const T& element) - { - if (m_count == m_capacity) - { - T* old = m_stack; - m_capacity *= 2; - m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); - std::memcpy(m_stack, old, m_count * sizeof(T)); - if (old != m_array) - { - b2Free(old); - } - } + void Push(const T& element) + { + if (m_count == m_capacity) + { + T* old = m_stack; + m_capacity *= 2; + m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); + memcpy(m_stack, old, m_count * sizeof(T)); + if (old != m_array) + { + b2Free(old); + } + } - m_stack[m_count] = element; - ++m_count; - } + m_stack[m_count] = element; + ++m_count; + } - T Pop() - { - b2Assert(m_count > 0); - --m_count; - return m_stack[m_count]; - } + T Pop() + { + b2Assert(m_count > 0); + --m_count; + return m_stack[m_count]; + } - int32 GetCount() - { - return m_count; - } + int32 GetCount() + { + return m_count; + } private: - T* m_stack; - T m_array[N]; - int32 m_count; - int32 m_capacity; + T* m_stack; + T m_array[N]; + int32 m_count; + int32 m_capacity; }; diff --git a/external/Box2D/Common/b2Math.cpp b/external/Box2D/Common/b2Math.cpp index 15d68fce96..d6027be90f 100644 --- a/external/Box2D/Common/b2Math.cpp +++ b/external/Box2D/Common/b2Math.cpp @@ -24,71 +24,71 @@ const b2Vec2 b2Vec2_zero(0.0f, 0.0f); /// than computing the inverse in one-shot cases. b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const { - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec3 x; - x.x = det * b2Dot(b, b2Cross(ey, ez)); - x.y = det * b2Dot(ex, b2Cross(b, ez)); - x.z = det * b2Dot(ex, b2Cross(ey, b)); - return x; + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec3 x; + x.x = det * b2Dot(b, b2Cross(ey, ez)); + x.y = det * b2Dot(ex, b2Cross(b, ez)); + x.z = det * b2Dot(ex, b2Cross(ey, b)); + return x; } /// Solve A * x = b, where b is a column vector. This is more efficient /// than computing the inverse in one-shot cases. b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const { - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; } /// void b2Mat33::GetInverse22(b2Mat33* M) const { - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } - M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; - M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; - M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; + M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; + M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; + M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; } /// Returns the zero matrix if singular. void b2Mat33::GetSymInverse33(b2Mat33* M) const { - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } + float32 det = b2Dot(ex, b2Cross(ey, ez)); + if (det != 0.0f) + { + det = 1.0f / det; + } - float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; - float32 a22 = ey.y, a23 = ez.y; - float32 a33 = ez.z; + float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; + float32 a22 = ey.y, a23 = ez.y; + float32 a33 = ez.z; - M->ex.x = det * (a22 * a33 - a23 * a23); - M->ex.y = det * (a13 * a23 - a12 * a33); - M->ex.z = det * (a12 * a23 - a13 * a22); + M->ex.x = det * (a22 * a33 - a23 * a23); + M->ex.y = det * (a13 * a23 - a12 * a33); + M->ex.z = det * (a12 * a23 - a13 * a22); - M->ey.x = M->ex.y; - M->ey.y = det * (a11 * a33 - a13 * a13); - M->ey.z = det * (a13 * a12 - a11 * a23); + M->ey.x = M->ex.y; + M->ey.y = det * (a11 * a33 - a13 * a13); + M->ey.z = det * (a13 * a12 - a11 * a23); - M->ez.x = M->ex.z; - M->ez.y = M->ey.z; - M->ez.z = det * (a11 * a22 - a12 * a12); + M->ez.x = M->ex.z; + M->ez.y = M->ey.z; + M->ez.z = det * (a11 * a22 - a12 * a12); } diff --git a/external/Box2D/Common/b2Math.h b/external/Box2D/Common/b2Math.h index a6be671139..755c519b0a 100644 --- a/external/Box2D/Common/b2Math.h +++ b/external/Box2D/Common/b2Math.h @@ -20,375 +20,357 @@ #define B2_MATH_H #include +#include -#include -#ifndef SHP -#include -#else -#include -#endif -#include -#include - -using namespace std; - - -/// This function is used to ensure that a floating point number is -/// not a NaN or infinity. +/// This function is used to ensure that a floating point number is not a NaN or infinity. inline bool b2IsValid(float32 x) { - if (x != x) - { - // NaN. - return false; - } - - float32 infinity = std::numeric_limits::infinity(); - return -infinity < x && x < infinity; + int32 ix = *reinterpret_cast(&x); + return (ix & 0x7f800000) != 0x7f800000; } /// This is a approximate yet fast inverse square-root. inline float32 b2InvSqrt(float32 x) { - union - { - float32 x; - int32 i; - } convert; + union + { + float32 x; + int32 i; + } convert; - convert.x = x; - float32 xhalf = 0.5f * x; - convert.i = 0x5f3759df - (convert.i >> 1); - x = convert.x; - x = x * (1.5f - xhalf * x * x); - return x; + convert.x = x; + float32 xhalf = 0.5f * x; + convert.i = 0x5f3759df - (convert.i >> 1); + x = convert.x; + x = x * (1.5f - xhalf * x * x); + return x; } -#define b2Sqrt(x) std::sqrt(x) -#define b2Atan2(y, x) std::atan2(y, x) +#define b2Sqrt(x) sqrtf(x) +#define b2Atan2(y, x) atan2f(y, x) /// A 2D column vector. struct b2Vec2 { - /// Default constructor does nothing (for performance). - b2Vec2() {} + /// Default constructor does nothing (for performance). + b2Vec2() {} - /// Construct using coordinates. - b2Vec2(float32 x, float32 y) : x(x), y(y) {} + /// Construct using coordinates. + b2Vec2(float32 x, float32 y) : x(x), y(y) {} - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; } + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; } - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_) { x = x_; y = y_; } + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_) { x = x_; y = y_; } - /// Negate this vector. - b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } - - /// Read from and indexed element. - float32 operator () (int32 i) const - { - return (&x)[i]; - } + /// Negate this vector. + b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } + + /// Read from and indexed element. + float32 operator () (int32 i) const + { + return (&x)[i]; + } - /// Write to an indexed element. - float32& operator () (int32 i) - { - return (&x)[i]; - } + /// Write to an indexed element. + float32& operator () (int32 i) + { + return (&x)[i]; + } - /// Add a vector to this vector. - void operator += (const b2Vec2& v) - { - x += v.x; y += v.y; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec2& v) - { - x -= v.x; y -= v.y; - } + /// Add a vector to this vector. + void operator += (const b2Vec2& v) + { + x += v.x; y += v.y; + } + + /// Subtract a vector from this vector. + void operator -= (const b2Vec2& v) + { + x -= v.x; y -= v.y; + } - /// Multiply this vector by a scalar. - void operator *= (float32 a) - { - x *= a; y *= a; - } + /// Multiply this vector by a scalar. + void operator *= (float32 a) + { + x *= a; y *= a; + } - /// Get the length of this vector (the norm). - float32 Length() const - { - return b2Sqrt(x * x + y * y); - } + /// Get the length of this vector (the norm). + float32 Length() const + { + return b2Sqrt(x * x + y * y); + } - /// Get the length squared. For performance, use this instead of - /// b2Vec2::Length (if possible). - float32 LengthSquared() const - { - return x * x + y * y; - } + /// Get the length squared. For performance, use this instead of + /// b2Vec2::Length (if possible). + float32 LengthSquared() const + { + return x * x + y * y; + } - /// Convert this vector into a unit vector. Returns the length. - float32 Normalize() - { - float32 length = Length(); - if (length < b2_epsilon) - { - return 0.0f; - } - float32 invLength = 1.0f / length; - x *= invLength; - y *= invLength; + /// Convert this vector into a unit vector. Returns the length. + float32 Normalize() + { + float32 length = Length(); + if (length < b2_epsilon) + { + return 0.0f; + } + float32 invLength = 1.0f / length; + x *= invLength; + y *= invLength; - return length; - } + return length; + } - /// Does this vector contain finite coordinates? - bool IsValid() const - { - return b2IsValid(x) && b2IsValid(y); - } + /// Does this vector contain finite coordinates? + bool IsValid() const + { + return b2IsValid(x) && b2IsValid(y); + } - /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - b2Vec2 Skew() const - { - return b2Vec2(-y, x); - } + /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) + b2Vec2 Skew() const + { + return b2Vec2(-y, x); + } - float32 x, y; + float32 x, y; }; /// A 2D column vector with 3 elements. struct b2Vec3 { - /// Default constructor does nothing (for performance). - b2Vec3() {} + /// Default constructor does nothing (for performance). + b2Vec3() {} - /// Construct using coordinates. - b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} + /// Construct using coordinates. + b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } + /// Set this vector to all zeros. + void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } + /// Set this vector to some specified coordinates. + void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } - /// Negate this vector. - b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } + /// Negate this vector. + b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } - /// Add a vector to this vector. - void operator += (const b2Vec3& v) - { - x += v.x; y += v.y; z += v.z; - } + /// Add a vector to this vector. + void operator += (const b2Vec3& v) + { + x += v.x; y += v.y; z += v.z; + } - /// Subtract a vector from this vector. - void operator -= (const b2Vec3& v) - { - x -= v.x; y -= v.y; z -= v.z; - } + /// Subtract a vector from this vector. + void operator -= (const b2Vec3& v) + { + x -= v.x; y -= v.y; z -= v.z; + } - /// Multiply this vector by a scalar. - void operator *= (float32 s) - { - x *= s; y *= s; z *= s; - } + /// Multiply this vector by a scalar. + void operator *= (float32 s) + { + x *= s; y *= s; z *= s; + } - float32 x, y, z; + float32 x, y, z; }; /// A 2-by-2 matrix. Stored in column-major order. struct b2Mat22 { - /// The default constructor does nothing (for performance). - b2Mat22() {} + /// The default constructor does nothing (for performance). + b2Mat22() {} - /// Construct this matrix using columns. - b2Mat22(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } + /// Construct this matrix using columns. + b2Mat22(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } - /// Construct this matrix using scalars. - b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) - { - ex.x = a11; ex.y = a21; - ey.x = a12; ey.y = a22; - } + /// Construct this matrix using scalars. + b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) + { + ex.x = a11; ex.y = a21; + ey.x = a12; ey.y = a22; + } - /// Initialize this matrix using columns. - void Set(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } + /// Initialize this matrix using columns. + void Set(const b2Vec2& c1, const b2Vec2& c2) + { + ex = c1; + ey = c2; + } - /// Set this to the identity matrix. - void SetIdentity() - { - ex.x = 1.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 1.0f; - } + /// Set this to the identity matrix. + void SetIdentity() + { + ex.x = 1.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 1.0f; + } - /// Set this matrix to all zeros. - void SetZero() - { - ex.x = 0.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 0.0f; - } + /// Set this matrix to all zeros. + void SetZero() + { + ex.x = 0.0f; ey.x = 0.0f; + ex.y = 0.0f; ey.y = 0.0f; + } - b2Mat22 GetInverse() const - { - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - b2Mat22 B; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - B.ex.x = det * d; B.ey.x = -det * b; - B.ex.y = -det * c; B.ey.y = det * a; - return B; - } + b2Mat22 GetInverse() const + { + float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; + b2Mat22 B; + float32 det = a * d - b * c; + if (det != 0.0f) + { + det = 1.0f / det; + } + B.ex.x = det * d; B.ey.x = -det * b; + B.ex.y = -det * c; B.ey.y = det * a; + return B; + } - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec2 Solve(const b2Vec2& b) const - { - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; - } + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec2 Solve(const b2Vec2& b) const + { + float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; + float32 det = a11 * a22 - a12 * a21; + if (det != 0.0f) + { + det = 1.0f / det; + } + b2Vec2 x; + x.x = det * (a22 * b.x - a12 * b.y); + x.y = det * (a11 * b.y - a21 * b.x); + return x; + } - b2Vec2 ex, ey; + b2Vec2 ex, ey; }; /// A 3-by-3 matrix. Stored in column-major order. struct b2Mat33 { - /// The default constructor does nothing (for performance). - b2Mat33() {} + /// The default constructor does nothing (for performance). + b2Mat33() {} - /// Construct this matrix using columns. - b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) - { - ex = c1; - ey = c2; - ez = c3; - } + /// Construct this matrix using columns. + b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) + { + ex = c1; + ey = c2; + ez = c3; + } - /// Set this matrix to all zeros. - void SetZero() - { - ex.SetZero(); - ey.SetZero(); - ez.SetZero(); - } + /// Set this matrix to all zeros. + void SetZero() + { + ex.SetZero(); + ey.SetZero(); + ez.SetZero(); + } - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec3 Solve33(const b2Vec3& b) const; + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. + b2Vec3 Solve33(const b2Vec3& b) const; - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. Solve only the upper - /// 2-by-2 matrix equation. - b2Vec2 Solve22(const b2Vec2& b) const; + /// Solve A * x = b, where b is a column vector. This is more efficient + /// than computing the inverse in one-shot cases. Solve only the upper + /// 2-by-2 matrix equation. + b2Vec2 Solve22(const b2Vec2& b) const; - /// Get the inverse of this matrix as a 2-by-2. - /// Returns the zero matrix if singular. - void GetInverse22(b2Mat33* M) const; + /// Get the inverse of this matrix as a 2-by-2. + /// Returns the zero matrix if singular. + void GetInverse22(b2Mat33* M) const; - /// Get the symmetric inverse of this matrix as a 3-by-3. - /// Returns the zero matrix if singular. - void GetSymInverse33(b2Mat33* M) const; + /// Get the symmetric inverse of this matrix as a 3-by-3. + /// Returns the zero matrix if singular. + void GetSymInverse33(b2Mat33* M) const; - b2Vec3 ex, ey, ez; + b2Vec3 ex, ey, ez; }; /// Rotation struct b2Rot { - b2Rot() {} + b2Rot() {} - /// Initialize from an angle in radians - explicit b2Rot(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } + /// Initialize from an angle in radians + explicit b2Rot(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } - /// Set using an angle in radians. - void Set(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } + /// Set using an angle in radians. + void Set(float32 angle) + { + /// TODO_ERIN optimize + s = sinf(angle); + c = cosf(angle); + } - /// Set to the identity rotation - void SetIdentity() - { - s = 0.0f; - c = 1.0f; - } + /// Set to the identity rotation + void SetIdentity() + { + s = 0.0f; + c = 1.0f; + } - /// Get the angle in radians - float32 GetAngle() const - { - return b2Atan2(s, c); - } + /// Get the angle in radians + float32 GetAngle() const + { + return b2Atan2(s, c); + } - /// Get the x-axis - b2Vec2 GetXAxis() const - { - return b2Vec2(c, s); - } + /// Get the x-axis + b2Vec2 GetXAxis() const + { + return b2Vec2(c, s); + } - /// Get the u-axis - b2Vec2 GetYAxis() const - { - return b2Vec2(-s, c); - } + /// Get the u-axis + b2Vec2 GetYAxis() const + { + return b2Vec2(-s, c); + } - /// Sine and cosine - float32 s, c; + /// Sine and cosine + float32 s, c; }; /// A transform contains translation and rotation. It is used to represent /// the position and orientation of rigid frames. struct b2Transform { - /// The default constructor does nothing. - b2Transform() {} + /// The default constructor does nothing. + b2Transform() {} - /// Initialize using a position vector and a rotation. - b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} + /// Initialize using a position vector and a rotation. + b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} - /// Set this to the identity transform. - void SetIdentity() - { - p.SetZero(); - q.SetIdentity(); - } + /// Set this to the identity transform. + void SetIdentity() + { + p.SetZero(); + q.SetIdentity(); + } - /// Set this based on the position and angle. - void Set(const b2Vec2& position, float32 angle) - { - p = position; - q.Set(angle); - } + /// Set this based on the position and angle. + void Set(const b2Vec2& position, float32 angle) + { + p = position; + q.Set(angle); + } - b2Vec2 p; - b2Rot q; + b2Vec2 p; + b2Rot q; }; /// This describes the motion of a body/shape for TOI computation. @@ -397,24 +379,24 @@ struct b2Transform /// we must interpolate the center of mass position. struct b2Sweep { - /// Get the interpolated transform at a specific time. - /// @param beta is a factor in [0,1], where 0 indicates alpha0. - void GetTransform(b2Transform* xfb, float32 beta) const; + /// Get the interpolated transform at a specific time. + /// @param beta is a factor in [0,1], where 0 indicates alpha0. + void GetTransform(b2Transform* xfb, float32 beta) const; - /// Advance the sweep forward, yielding a new initial state. - /// @param alpha the new initial time. - void Advance(float32 alpha); + /// Advance the sweep forward, yielding a new initial state. + /// @param alpha the new initial time. + void Advance(float32 alpha); - /// Normalize the angles. - void Normalize(); + /// Normalize the angles. + void Normalize(); - b2Vec2 localCenter; ///< local center of mass position - b2Vec2 c0, c; ///< center world positions - float32 a0, a; ///< world angles + b2Vec2 localCenter; ///< local center of mass position + b2Vec2 c0, c; ///< center world positions + float32 a0, a; ///< world angles - /// Fraction of the current time step in the range [0,1] - /// c0 and a0 are the positions at alpha0. - float32 alpha0; + /// Fraction of the current time step in the range [0,1] + /// c0 and a0 are the positions at alpha0. + float32 alpha0; }; /// Useful constant @@ -423,267 +405,267 @@ extern const b2Vec2 b2Vec2_zero; /// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) { - return a.x * b.x + a.y * b.y; + return a.x * b.x + a.y * b.y; } /// Perform the cross product on two vectors. In 2D this produces a scalar. inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) { - return a.x * b.y - a.y * b.x; + return a.x * b.y - a.y * b.x; } /// Perform the cross product on a vector and a scalar. In 2D this produces /// a vector. inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) { - return b2Vec2(s * a.y, -s * a.x); + return b2Vec2(s * a.y, -s * a.x); } /// Perform the cross product on a scalar and a vector. In 2D this produces /// a vector. inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) { - return b2Vec2(-s * a.y, s * a.x); + return b2Vec2(-s * a.y, s * a.x); } /// Multiply a matrix times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another. inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) { - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); } /// Multiply a matrix transpose times a vector. If a rotation matrix is provided, /// then this transforms the vector from one frame to another (inverse transform). inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) { - return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); + return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); } /// Add two vectors component-wise. inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) { - return b2Vec2(a.x + b.x, a.y + b.y); + return b2Vec2(a.x + b.x, a.y + b.y); } /// Subtract two vectors component-wise. inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) { - return b2Vec2(a.x - b.x, a.y - b.y); + return b2Vec2(a.x - b.x, a.y - b.y); } inline b2Vec2 operator * (float32 s, const b2Vec2& a) { - return b2Vec2(s * a.x, s * a.y); + return b2Vec2(s * a.x, s * a.y); } inline bool operator == (const b2Vec2& a, const b2Vec2& b) { - return a.x == b.x && a.y == b.y; + return a.x == b.x && a.y == b.y; } inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) { - b2Vec2 c = a - b; - return c.Length(); + b2Vec2 c = a - b; + return c.Length(); } inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) { - b2Vec2 c = a - b; - return b2Dot(c, c); + b2Vec2 c = a - b; + return b2Dot(c, c); } inline b2Vec3 operator * (float32 s, const b2Vec3& a) { - return b2Vec3(s * a.x, s * a.y, s * a.z); + return b2Vec3(s * a.x, s * a.y, s * a.z); } /// Add two vectors component-wise. inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) { - return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); + return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); } /// Subtract two vectors component-wise. inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) { - return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); + return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); } /// Perform the dot product on two vectors. inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) { - return a.x * b.x + a.y * b.y + a.z * b.z; + return a.x * b.x + a.y * b.y + a.z * b.z; } /// Perform the cross product on two vectors. inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) { - return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); + return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); } inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) { - return b2Mat22(A.ex + B.ex, A.ey + B.ey); + return b2Mat22(A.ex + B.ex, A.ey + B.ey); } // A * B inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) { - return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); + return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); } // A^T * B inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) { - b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); - b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); - return b2Mat22(c1, c2); + b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); + b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); + return b2Mat22(c1, c2); } /// Multiply a matrix times a vector. inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) { - return v.x * A.ex + v.y * A.ey + v.z * A.ez; + return v.x * A.ex + v.y * A.ey + v.z * A.ez; } /// Multiply a matrix times a vector. inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) { - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); + return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); } /// Multiply two rotations: q * r inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) { - // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] - // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] - // s = qs * rc + qc * rs - // c = qc * rc - qs * rs - b2Rot qr; - qr.s = q.s * r.c + q.c * r.s; - qr.c = q.c * r.c - q.s * r.s; - return qr; + // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] + // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] + // s = qs * rc + qc * rs + // c = qc * rc - qs * rs + b2Rot qr; + qr.s = q.s * r.c + q.c * r.s; + qr.c = q.c * r.c - q.s * r.s; + return qr; } /// Transpose multiply two rotations: qT * r inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) { - // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] - // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] - // s = qc * rs - qs * rc - // c = qc * rc + qs * rs - b2Rot qr; - qr.s = q.c * r.s - q.s * r.c; - qr.c = q.c * r.c + q.s * r.s; - return qr; + // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] + // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] + // s = qc * rs - qs * rc + // c = qc * rc + qs * rs + b2Rot qr; + qr.s = q.c * r.s - q.s * r.c; + qr.c = q.c * r.c + q.s * r.s; + return qr; } /// Rotate a vector inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) { - return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); + return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); } /// Inverse rotate a vector inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) { - return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); + return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); } inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) { - float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; - float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; + float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; + float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; - return b2Vec2(x, y); + return b2Vec2(x, y); } inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) { - float32 px = v.x - T.p.x; - float32 py = v.y - T.p.y; - float32 x = (T.q.c * px + T.q.s * py); - float32 y = (-T.q.s * px + T.q.c * py); + float32 px = v.x - T.p.x; + float32 py = v.y - T.p.y; + float32 x = (T.q.c * px + T.q.s * py); + float32 y = (-T.q.s * px + T.q.c * py); - return b2Vec2(x, y); + return b2Vec2(x, y); } // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p // = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) { - b2Transform C; - C.q = b2Mul(A.q, B.q); - C.p = b2Mul(A.q, B.p) + A.p; - return C; + b2Transform C; + C.q = b2Mul(A.q, B.q); + C.p = b2Mul(A.q, B.p) + A.p; + return C; } // v2 = A.q' * (B.q * v1 + B.p - A.p) // = A.q' * B.q * v1 + A.q' * (B.p - A.p) inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) { - b2Transform C; - C.q = b2MulT(A.q, B.q); - C.p = b2MulT(A.q, B.p - A.p); - return C; + b2Transform C; + C.q = b2MulT(A.q, B.q); + C.p = b2MulT(A.q, B.p - A.p); + return C; } template inline T b2Abs(T a) { - return a > T(0) ? a : -a; + return a > T(0) ? a : -a; } inline b2Vec2 b2Abs(const b2Vec2& a) { - return b2Vec2(b2Abs(a.x), b2Abs(a.y)); + return b2Vec2(b2Abs(a.x), b2Abs(a.y)); } inline b2Mat22 b2Abs(const b2Mat22& A) { - return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); + return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); } template inline T b2Min(T a, T b) { - return a < b ? a : b; + return a < b ? a : b; } inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) { - return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); + return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); } template inline T b2Max(T a, T b) { - return a > b ? a : b; + return a > b ? a : b; } inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) { - return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); + return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); } template inline T b2Clamp(T a, T low, T high) { - return b2Max(low, b2Min(a, high)); + return b2Max(low, b2Min(a, high)); } inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) { - return b2Max(low, b2Min(a, high)); + return b2Max(low, b2Min(a, high)); } template inline void b2Swap(T& a, T& b) { - T tmp = a; - a = b; - b = tmp; + T tmp = a; + a = b; + b = tmp; } /// "Next Largest Power of 2 @@ -693,46 +675,46 @@ template inline void b2Swap(T& a, T& b) /// largest power of 2. For a 32-bit value:" inline uint32 b2NextPowerOfTwo(uint32 x) { - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - return x + 1; + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x + 1; } inline bool b2IsPowerOfTwo(uint32 x) { - bool result = x > 0 && (x & (x - 1)) == 0; - return result; + bool result = x > 0 && (x & (x - 1)) == 0; + return result; } inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const { - xf->p = (1.0f - beta) * c0 + beta * c; - float32 angle = (1.0f - beta) * a0 + beta * a; - xf->q.Set(angle); + xf->p = (1.0f - beta) * c0 + beta * c; + float32 angle = (1.0f - beta) * a0 + beta * a; + xf->q.Set(angle); - // Shift to origin - xf->p -= b2Mul(xf->q, localCenter); + // Shift to origin + xf->p -= b2Mul(xf->q, localCenter); } inline void b2Sweep::Advance(float32 alpha) { - b2Assert(alpha0 < 1.0f); - float32 beta = (alpha - alpha0) / (1.0f - alpha0); - c0 = (1.0f - beta) * c0 + beta * c; - a0 = (1.0f - beta) * a0 + beta * a; - alpha0 = alpha; + b2Assert(alpha0 < 1.0f); + float32 beta = (alpha - alpha0) / (1.0f - alpha0); + c0 += beta * (c - c0); + a0 += beta * (a - a0); + alpha0 = alpha; } /// Normalize an angle in radians to be between -pi and pi inline void b2Sweep::Normalize() { - float32 twoPi = 2.0f * b2_pi; - float32 d = twoPi * floorf(a0 / twoPi); - a0 -= d; - a -= d; + float32 twoPi = 2.0f * b2_pi; + float32 d = twoPi * floorf(a0 / twoPi); + a0 -= d; + a -= d; } #endif diff --git a/external/Box2D/Common/b2Settings.cpp b/external/Box2D/Common/b2Settings.cpp index 84d6f1d0e4..c780260800 100644 --- a/external/Box2D/Common/b2Settings.cpp +++ b/external/Box2D/Common/b2Settings.cpp @@ -17,45 +17,28 @@ */ #include -#ifdef SHP -#include #include -#include #include -#else -#include -#include -#include -#endif +#include - -using namespace std; - - -b2Version b2_version = {2, 2, 1}; +b2Version b2_version = {2, 3, 0}; // Memory allocators. Modify these to use your own allocator. void* b2Alloc(int32 size) { - return malloc(size); + return malloc(size); } void b2Free(void* mem) { - free(mem); + free(mem); } // You can modify this to use your logging facility. void b2Log(const char* string, ...) { -#if defined(SHP) - #ifdef _DEBUG - __App_info(__PRETTY_FUNCTION__ , __LINE__, string); - #endif -#else - va_list args; - va_start(args, string); - vprintf(string, args); - va_end(args); -#endif + va_list args; + va_start(args, string); + vprintf(string, args); + va_end(args); } diff --git a/external/Box2D/Common/b2Settings.h b/external/Box2D/Common/b2Settings.h index aaf4b12ccf..86f76bd267 100644 --- a/external/Box2D/Common/b2Settings.h +++ b/external/Box2D/Common/b2Settings.h @@ -19,13 +19,14 @@ #ifndef B2_SETTINGS_H #define B2_SETTINGS_H -#include -#include +#include +#include +#include #define B2_NOT_USED(x) ((void)(x)) #define b2Assert(A) assert(A) -typedef signed char int8; +typedef signed char int8; typedef signed short int16; typedef signed int int32; typedef unsigned char uint8; @@ -34,9 +35,9 @@ typedef unsigned int uint32; typedef float float32; typedef double float64; -#define b2_maxFloat FLT_MAX -#define b2_epsilon FLT_EPSILON -#define b2_pi 3.14159265359f +#define b2_maxFloat FLT_MAX +#define b2_epsilon FLT_EPSILON +#define b2_pi 3.14159265359f /// @file /// Global tuning constants based on meters-kilograms-seconds (MKS) units. @@ -46,83 +47,83 @@ typedef double float64; /// The maximum number of contact points between two convex shapes. Do /// not change this value. -#define b2_maxManifoldPoints 2 +#define b2_maxManifoldPoints 2 /// The maximum number of vertices on a convex polygon. You cannot increase /// this too much because b2BlockAllocator has a maximum object size. -#define b2_maxPolygonVertices 8 +#define b2_maxPolygonVertices 8 /// This is used to fatten AABBs in the dynamic tree. This allows proxies /// to move by a small amount without triggering a tree adjustment. /// This is in meters. -#define b2_aabbExtension 0.1f +#define b2_aabbExtension 0.1f /// This is used to fatten AABBs in the dynamic tree. This is used to predict /// the future position based on the current displacement. /// This is a dimensionless multiplier. -#define b2_aabbMultiplier 2.0f +#define b2_aabbMultiplier 2.0f /// A small length used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. -#define b2_linearSlop 0.005f +#define b2_linearSlop 0.005f /// A small angle used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. -#define b2_angularSlop (2.0f / 180.0f * b2_pi) +#define b2_angularSlop (2.0f / 180.0f * b2_pi) /// The radius of the polygon/edge shape skin. This should not be modified. Making /// this smaller means polygons will have an insufficient buffer for continuous collision. /// Making it larger may create artifacts for vertex collision. -#define b2_polygonRadius (2.0f * b2_linearSlop) +#define b2_polygonRadius (2.0f * b2_linearSlop) /// Maximum number of sub-steps per contact in continuous physics simulation. -#define b2_maxSubSteps 8 +#define b2_maxSubSteps 8 // Dynamics /// Maximum number of contacts to be handled to solve a TOI impact. -#define b2_maxTOIContacts 32 +#define b2_maxTOIContacts 32 /// A velocity threshold for elastic collisions. Any collision with a relative linear /// velocity below this threshold will be treated as inelastic. -#define b2_velocityThreshold 1.0f +#define b2_velocityThreshold 1.0f /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. -#define b2_maxLinearCorrection 0.2f +#define b2_maxLinearCorrection 0.2f /// The maximum angular position correction used when solving constraints. This helps to /// prevent overshoot. -#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) +#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxTranslation 2.0f -#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) +#define b2_maxTranslation 2.0f +#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxRotation (0.5f * b2_pi) -#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) +#define b2_maxRotation (0.5f * b2_pi) +#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However using values close to 1 often lead /// to overshoot. -#define b2_baumgarte 0.2f -#define b2_toiBaugarte 0.75f +#define b2_baumgarte 0.2f +#define b2_toiBaugarte 0.75f // Sleep /// The time that a body must be still before it will go to sleep. -#define b2_timeToSleep 0.5f +#define b2_timeToSleep 0.5f /// A body cannot sleep if its linear velocity is above this tolerance. -#define b2_linearSleepTolerance 0.01f +#define b2_linearSleepTolerance 0.01f /// A body cannot sleep if its angular velocity is above this tolerance. -#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) +#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) // Memory Allocation @@ -139,9 +140,9 @@ void b2Log(const char* string, ...); /// See http://en.wikipedia.org/wiki/Software_versioning struct b2Version { - int32 major; ///< significant changes - int32 minor; ///< incremental changes - int32 revision; ///< bug fixes + int32 major; ///< significant changes + int32 minor; ///< incremental changes + int32 revision; ///< bug fixes }; /// Current version. diff --git a/external/Box2D/Common/b2StackAllocator.cpp b/external/Box2D/Common/b2StackAllocator.cpp index 3caa5d9127..321cabb232 100644 --- a/external/Box2D/Common/b2StackAllocator.cpp +++ b/external/Box2D/Common/b2StackAllocator.cpp @@ -21,63 +21,63 @@ b2StackAllocator::b2StackAllocator() { - m_index = 0; - m_allocation = 0; - m_maxAllocation = 0; - m_entryCount = 0; + m_index = 0; + m_allocation = 0; + m_maxAllocation = 0; + m_entryCount = 0; } b2StackAllocator::~b2StackAllocator() { - b2Assert(m_index == 0); - b2Assert(m_entryCount == 0); + b2Assert(m_index == 0); + b2Assert(m_entryCount == 0); } void* b2StackAllocator::Allocate(int32 size) { - b2Assert(m_entryCount < b2_maxStackEntries); + b2Assert(m_entryCount < b2_maxStackEntries); - b2StackEntry* entry = m_entries + m_entryCount; - entry->size = size; - if (m_index + size > b2_stackSize) - { - entry->data = (char*)b2Alloc(size); - entry->usedMalloc = true; - } - else - { - entry->data = m_data + m_index; - entry->usedMalloc = false; - m_index += size; - } + b2StackEntry* entry = m_entries + m_entryCount; + entry->size = size; + if (m_index + size > b2_stackSize) + { + entry->data = (char*)b2Alloc(size); + entry->usedMalloc = true; + } + else + { + entry->data = m_data + m_index; + entry->usedMalloc = false; + m_index += size; + } - m_allocation += size; - m_maxAllocation = b2Max(m_maxAllocation, m_allocation); - ++m_entryCount; + m_allocation += size; + m_maxAllocation = b2Max(m_maxAllocation, m_allocation); + ++m_entryCount; - return entry->data; + return entry->data; } void b2StackAllocator::Free(void* p) { - b2Assert(m_entryCount > 0); - b2StackEntry* entry = m_entries + m_entryCount - 1; - b2Assert(p == entry->data); - if (entry->usedMalloc) - { - b2Free(p); - } - else - { - m_index -= entry->size; - } - m_allocation -= entry->size; - --m_entryCount; + b2Assert(m_entryCount > 0); + b2StackEntry* entry = m_entries + m_entryCount - 1; + b2Assert(p == entry->data); + if (entry->usedMalloc) + { + b2Free(p); + } + else + { + m_index -= entry->size; + } + m_allocation -= entry->size; + --m_entryCount; - p = NULL; + p = NULL; } int32 b2StackAllocator::GetMaxAllocation() const { - return m_maxAllocation; + return m_maxAllocation; } diff --git a/external/Box2D/Common/b2StackAllocator.h b/external/Box2D/Common/b2StackAllocator.h index 6140d0d802..bb87a7edc9 100644 --- a/external/Box2D/Common/b2StackAllocator.h +++ b/external/Box2D/Common/b2StackAllocator.h @@ -21,14 +21,14 @@ #include -const int32 b2_stackSize = 100 * 1024; // 100k +const int32 b2_stackSize = 100 * 1024; // 100k const int32 b2_maxStackEntries = 32; struct b2StackEntry { - char* data; - int32 size; - bool usedMalloc; + char* data; + int32 size; + bool usedMalloc; }; // This is a stack allocator used for fast per step allocations. @@ -37,24 +37,24 @@ struct b2StackEntry class b2StackAllocator { public: - b2StackAllocator(); - ~b2StackAllocator(); + b2StackAllocator(); + ~b2StackAllocator(); - void* Allocate(int32 size); - void Free(void* p); + void* Allocate(int32 size); + void Free(void* p); - int32 GetMaxAllocation() const; + int32 GetMaxAllocation() const; private: - char m_data[b2_stackSize]; - int32 m_index; + char m_data[b2_stackSize]; + int32 m_index; - int32 m_allocation; - int32 m_maxAllocation; + int32 m_allocation; + int32 m_maxAllocation; - b2StackEntry m_entries[b2_maxStackEntries]; - int32 m_entryCount; + b2StackEntry m_entries[b2_maxStackEntries]; + int32 m_entryCount; }; #endif diff --git a/external/Box2D/Common/b2Timer.cpp b/external/Box2D/Common/b2Timer.cpp index b2bee94513..cbea5309e4 100644 --- a/external/Box2D/Common/b2Timer.cpp +++ b/external/Box2D/Common/b2Timer.cpp @@ -18,44 +18,45 @@ #include -#if defined(_WIN32) && !defined(SHP) +#if defined(_WIN32) float64 b2Timer::s_invFrequency = 0.0f; +#define WIN32_LEAN_AND_MEAN #include b2Timer::b2Timer() { - LARGE_INTEGER largeInteger; + LARGE_INTEGER largeInteger; - if (s_invFrequency == 0.0f) - { - QueryPerformanceFrequency(&largeInteger); - s_invFrequency = float64(largeInteger.QuadPart); - if (s_invFrequency > 0.0f) - { - s_invFrequency = 1000.0f / s_invFrequency; - } - } + if (s_invFrequency == 0.0f) + { + QueryPerformanceFrequency(&largeInteger); + s_invFrequency = float64(largeInteger.QuadPart); + if (s_invFrequency > 0.0f) + { + s_invFrequency = 1000.0f / s_invFrequency; + } + } - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); } void b2Timer::Reset() { - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + m_start = float64(largeInteger.QuadPart); } float32 b2Timer::GetMilliseconds() const { - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - float64 count = float64(largeInteger.QuadPart); - float32 ms = float32(s_invFrequency * (count - m_start)); - return ms; + LARGE_INTEGER largeInteger; + QueryPerformanceCounter(&largeInteger); + float64 count = float64(largeInteger.QuadPart); + float32 ms = float32(s_invFrequency * (count - m_start)); + return ms; } #elif defined(__linux__) || defined (__APPLE__) @@ -72,14 +73,14 @@ void b2Timer::Reset() timeval t; gettimeofday(&t, 0); m_start_sec = t.tv_sec; - m_start_msec = t.tv_usec * 0.001f; + m_start_usec = t.tv_usec; } float32 b2Timer::GetMilliseconds() const { timeval t; gettimeofday(&t, 0); - return (t.tv_sec - m_start_sec) * 1000 + t.tv_usec * 0.001f - m_start_msec; + return 1000.0f * (t.tv_sec - m_start_sec) + 0.001f * (t.tv_usec - m_start_usec); } #else @@ -94,7 +95,7 @@ void b2Timer::Reset() float32 b2Timer::GetMilliseconds() const { - return 0.0f; + return 0.0f; } #endif diff --git a/external/Box2D/Common/b2Timer.h b/external/Box2D/Common/b2Timer.h index 053a107a56..edf1ca4595 100644 --- a/external/Box2D/Common/b2Timer.h +++ b/external/Box2D/Common/b2Timer.h @@ -16,6 +16,9 @@ * 3. This notice may not be removed or altered from any source distribution. */ +#ifndef B2_TIMER_H +#define B2_TIMER_H + #include /// Timer for profiling. This has platform specific code and may @@ -24,22 +27,24 @@ class b2Timer { public: - /// Constructor - b2Timer(); + /// Constructor + b2Timer(); - /// Reset the timer. - void Reset(); + /// Reset the timer. + void Reset(); - /// Get the time since construction or the last reset. - float32 GetMilliseconds() const; + /// Get the time since construction or the last reset. + float32 GetMilliseconds() const; private: #if defined(_WIN32) - float64 m_start; - static float64 s_invFrequency; + float64 m_start; + static float64 s_invFrequency; #elif defined(__linux__) || defined (__APPLE__) - unsigned long m_start_sec; - unsigned long m_start_msec; + unsigned long m_start_sec; + unsigned long m_start_usec; #endif }; + +#endif diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp index 4ae4c41cd3..01c921f3db 100644 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp @@ -23,32 +23,31 @@ #include #include -using namespace std; b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); - return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); + void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); + return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); } void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); - allocator->Free(contact, sizeof(b2ChainAndCircleContact)); + ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); + allocator->Free(contact, sizeof(b2ChainAndCircleContact)); } b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) : b2Contact(fixtureA, indexA, fixtureB, indexB) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); } void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndCircle( manifold, &edge, xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndCircle( manifold, &edge, xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h index 1cf601a61f..b93c30edc4 100644 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2ChainAndCircleContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndCircleContact() {} + b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndCircleContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp index 8116c34d1b..4642fa46ab 100644 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp @@ -23,32 +23,31 @@ #include #include -using namespace std; b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); - return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); + void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); + return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); } void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); - allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); + ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); + allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); } b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) : b2Contact(fixtureA, indexA, fixtureB, indexB) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); } void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndPolygon( manifold, &edge, xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); + b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); + b2EdgeShape edge; + chain->GetChildEdge(&edge, m_indexA); + b2CollideEdgeAndPolygon( manifold, &edge, xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h index 381c49b844..0c09af68a1 100644 --- a/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h +++ b/external/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2ChainAndPolygonContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndPolygonContact() {} + b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + ~b2ChainAndPolygonContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp index 2436da5132..b47f35aed0 100644 --- a/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2CircleContact.cpp @@ -24,30 +24,29 @@ #include #include -using namespace std; b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2CircleContact)); - return new (mem) b2CircleContact(fixtureA, fixtureB); + void* mem = allocator->Allocate(sizeof(b2CircleContact)); + return new (mem) b2CircleContact(fixtureA, fixtureB); } void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2CircleContact*)contact)->~b2CircleContact(); - allocator->Free(contact, sizeof(b2CircleContact)); + ((b2CircleContact*)contact)->~b2CircleContact(); + allocator->Free(contact, sizeof(b2CircleContact)); } b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) + : b2Contact(fixtureA, 0, fixtureB, 0) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); } void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2CollideCircles(manifold, - (b2CircleShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); + b2CollideCircles(manifold, + (b2CircleShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2CircleContact.h b/external/Box2D/Dynamics/Contacts/b2CircleContact.h index 6da056ae0d..079d3abcdb 100644 --- a/external/Box2D/Dynamics/Contacts/b2CircleContact.h +++ b/external/Box2D/Dynamics/Contacts/b2CircleContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2CircleContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2CircleContact() {} + b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2CircleContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.cpp b/external/Box2D/Dynamics/Contacts/b2Contact.cpp index 2389af6434..d9f1021e4d 100644 --- a/external/Box2D/Dynamics/Contacts/b2Contact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2Contact.cpp @@ -39,202 +39,209 @@ bool b2Contact::s_initialized = false; void b2Contact::InitializeRegisters() { - AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); - AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); - AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); - AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); - AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); - AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); - AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); + AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); + AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); + AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); + AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); + AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); + AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); + AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); } void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, - b2Shape::Type type1, b2Shape::Type type2) + b2Shape::Type type1, b2Shape::Type type2) { - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - s_registers[type1][type2].createFcn = createFcn; - s_registers[type1][type2].destroyFcn = destoryFcn; - s_registers[type1][type2].primary = true; + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + s_registers[type1][type2].createFcn = createFcn; + s_registers[type1][type2].destroyFcn = destoryFcn; + s_registers[type1][type2].primary = true; - if (type1 != type2) - { - s_registers[type2][type1].createFcn = createFcn; - s_registers[type2][type1].destroyFcn = destoryFcn; - s_registers[type2][type1].primary = false; - } + if (type1 != type2) + { + s_registers[type2][type1].createFcn = createFcn; + s_registers[type2][type1].destroyFcn = destoryFcn; + s_registers[type2][type1].primary = false; + } } b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { - if (s_initialized == false) - { - InitializeRegisters(); - s_initialized = true; - } + if (s_initialized == false) + { + InitializeRegisters(); + s_initialized = true; + } - b2Shape::Type type1 = fixtureA->GetType(); - b2Shape::Type type2 = fixtureB->GetType(); + b2Shape::Type type1 = fixtureA->GetType(); + b2Shape::Type type2 = fixtureB->GetType(); - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; - if (createFcn) - { - if (s_registers[type1][type2].primary) - { - return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); - } - else - { - return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); - } - } - else - { - return NULL; - } + b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); + b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); + + b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; + if (createFcn) + { + if (s_registers[type1][type2].primary) + { + return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); + } + else + { + return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); + } + } + else + { + return NULL; + } } void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - b2Assert(s_initialized == true); + b2Assert(s_initialized == true); - if (contact->m_manifold.pointCount > 0) - { - contact->GetFixtureA()->GetBody()->SetAwake(true); - contact->GetFixtureB()->GetBody()->SetAwake(true); - } + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; - b2Shape::Type typeA = contact->GetFixtureA()->GetType(); - b2Shape::Type typeB = contact->GetFixtureB()->GetType(); + if (contact->m_manifold.pointCount > 0 && + fixtureA->IsSensor() == false && + fixtureB->IsSensor() == false) + { + fixtureA->GetBody()->SetAwake(true); + fixtureB->GetBody()->SetAwake(true); + } - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + b2Shape::Type typeA = fixtureA->GetType(); + b2Shape::Type typeB = fixtureB->GetType(); - b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; - destroyFcn(contact, allocator); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); + + b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; + destroyFcn(contact, allocator); } b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) { - m_flags = e_enabledFlag; + m_flags = e_enabledFlag; - m_fixtureA = fA; - m_fixtureB = fB; + m_fixtureA = fA; + m_fixtureB = fB; - m_indexA = indexA; - m_indexB = indexB; + m_indexA = indexA; + m_indexB = indexB; - m_manifold.pointCount = 0; + m_manifold.pointCount = 0; - m_prev = NULL; - m_next = NULL; + m_prev = NULL; + m_next = NULL; - m_nodeA.contact = NULL; - m_nodeA.prev = NULL; - m_nodeA.next = NULL; - m_nodeA.other = NULL; + m_nodeA.contact = NULL; + m_nodeA.prev = NULL; + m_nodeA.next = NULL; + m_nodeA.other = NULL; - m_nodeB.contact = NULL; - m_nodeB.prev = NULL; - m_nodeB.next = NULL; - m_nodeB.other = NULL; + m_nodeB.contact = NULL; + m_nodeB.prev = NULL; + m_nodeB.next = NULL; + m_nodeB.other = NULL; - m_toiCount = 0; + m_toiCount = 0; - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); + + m_tangentSpeed = 0.0f; } // Update the contact manifold and touching status. // Note: do not assume the fixture AABBs are overlapping or are valid. void b2Contact::Update(b2ContactListener* listener) { - b2Manifold oldManifold = m_manifold; + b2Manifold oldManifold = m_manifold; - // Re-enable this contact. - m_flags |= e_enabledFlag; + // Re-enable this contact. + m_flags |= e_enabledFlag; - bool touching = false; - bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; + bool touching = false; + bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; - bool sensorA = m_fixtureA->IsSensor(); - bool sensorB = m_fixtureB->IsSensor(); - bool sensor = sensorA || sensorB; + bool sensorA = m_fixtureA->IsSensor(); + bool sensorB = m_fixtureB->IsSensor(); + bool sensor = sensorA || sensorB; - b2Body* bodyA = m_fixtureA->GetBody(); - b2Body* bodyB = m_fixtureB->GetBody(); - const b2Transform& xfA = bodyA->GetTransform(); - const b2Transform& xfB = bodyB->GetTransform(); + b2Body* bodyA = m_fixtureA->GetBody(); + b2Body* bodyB = m_fixtureB->GetBody(); + const b2Transform& xfA = bodyA->GetTransform(); + const b2Transform& xfB = bodyB->GetTransform(); - // Is this contact a sensor? - if (sensor) - { - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); + // Is this contact a sensor? + if (sensor) + { + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); + touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); - // Sensors don't generate manifolds. - m_manifold.pointCount = 0; - } - else - { - Evaluate(&m_manifold, xfA, xfB); - touching = m_manifold.pointCount > 0; + // Sensors don't generate manifolds. + m_manifold.pointCount = 0; + } + else + { + Evaluate(&m_manifold, xfA, xfB); + touching = m_manifold.pointCount > 0; - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp2 = m_manifold.points + i; - mp2->normalImpulse = 0.0f; - mp2->tangentImpulse = 0.0f; - b2ContactID id2 = mp2->id; + // Match old contact ids to new contact ids and copy the + // stored impulses to warm start the solver. + for (int32 i = 0; i < m_manifold.pointCount; ++i) + { + b2ManifoldPoint* mp2 = m_manifold.points + i; + mp2->normalImpulse = 0.0f; + mp2->tangentImpulse = 0.0f; + b2ContactID id2 = mp2->id; - for (int32 j = 0; j < oldManifold.pointCount; ++j) - { - b2ManifoldPoint* mp1 = oldManifold.points + j; + for (int32 j = 0; j < oldManifold.pointCount; ++j) + { + b2ManifoldPoint* mp1 = oldManifold.points + j; - if (mp1->id.key == id2.key) - { - mp2->normalImpulse = mp1->normalImpulse; - mp2->tangentImpulse = mp1->tangentImpulse; - break; - } - } - } + if (mp1->id.key == id2.key) + { + mp2->normalImpulse = mp1->normalImpulse; + mp2->tangentImpulse = mp1->tangentImpulse; + break; + } + } + } - if (touching != wasTouching) - { - bodyA->SetAwake(true); - bodyB->SetAwake(true); - } - } + if (touching != wasTouching) + { + bodyA->SetAwake(true); + bodyB->SetAwake(true); + } + } - if (touching) - { - m_flags |= e_touchingFlag; - } - else - { - m_flags &= ~e_touchingFlag; - } + if (touching) + { + m_flags |= e_touchingFlag; + } + else + { + m_flags &= ~e_touchingFlag; + } - if (wasTouching == false && touching == true && listener) - { - listener->BeginContact(this); - } + if (wasTouching == false && touching == true && listener) + { + listener->BeginContact(this); + } - if (wasTouching == true && touching == false && listener) - { - listener->EndContact(this); - } + if (wasTouching == true && touching == false && listener) + { + listener->EndContact(this); + } - if (sensor == false && touching && listener) - { - listener->PreSolve(this, &oldManifold); - } + if (sensor == false && touching && listener) + { + listener->PreSolve(this, &oldManifold); + } } diff --git a/external/Box2D/Dynamics/Contacts/b2Contact.h b/external/Box2D/Dynamics/Contacts/b2Contact.h index 20d9403ce7..36e31e2566 100644 --- a/external/Box2D/Dynamics/Contacts/b2Contact.h +++ b/external/Box2D/Dynamics/Contacts/b2Contact.h @@ -36,26 +36,26 @@ class b2ContactListener; /// For example, anything slides on ice. inline float32 b2MixFriction(float32 friction1, float32 friction2) { - return std::sqrt(friction1 * friction2); + return b2Sqrt(friction1 * friction2); } /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. /// For example, a superball bounces on anything. inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) { - return restitution1 > restitution2 ? restitution1 : restitution2; + return restitution1 > restitution2 ? restitution1 : restitution2; } -typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, - b2BlockAllocator* allocator); +typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, + b2BlockAllocator* allocator); typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); struct b2ContactRegister { - b2ContactCreateFcn* createFcn; - b2ContactDestroyFcn* destroyFcn; - bool primary; + b2ContactCreateFcn* createFcn; + b2ContactDestroyFcn* destroyFcn; + bool primary; }; /// A contact edge is used to connect bodies and contacts together @@ -65,10 +65,10 @@ struct b2ContactRegister /// nodes, one for each attached body. struct b2ContactEdge { - b2Body* other; ///< provides quick access to the other body attached. - b2Contact* contact; ///< the contact - b2ContactEdge* prev; ///< the previous contact edge in the body's contact list - b2ContactEdge* next; ///< the next contact edge in the body's contact list + b2Body* other; ///< provides quick access to the other body attached. + b2Contact* contact; ///< the contact + b2ContactEdge* prev; ///< the previous contact edge in the body's contact list + b2ContactEdge* next; ///< the next contact edge in the body's contact list }; /// The class manages contact between two shapes. A contact exists for each overlapping @@ -78,254 +78,272 @@ class b2Contact { public: - /// Get the contact manifold. Do not modify the manifold unless you understand the - /// internals of Box2D. - b2Manifold* GetManifold(); - const b2Manifold* GetManifold() const; + /// Get the contact manifold. Do not modify the manifold unless you understand the + /// internals of Box2D. + b2Manifold* GetManifold(); + const b2Manifold* GetManifold() const; - /// Get the world manifold. - void GetWorldManifold(b2WorldManifold* worldManifold) const; + /// Get the world manifold. + void GetWorldManifold(b2WorldManifold* worldManifold) const; - /// Is this contact touching? - bool IsTouching() const; + /// Is this contact touching? + bool IsTouching() const; - /// Enable/disable this contact. This can be used inside the pre-solve - /// contact listener. The contact is only disabled for the current - /// time step (or sub-step in continuous collisions). - void SetEnabled(bool flag); + /// Enable/disable this contact. This can be used inside the pre-solve + /// contact listener. The contact is only disabled for the current + /// time step (or sub-step in continuous collisions). + void SetEnabled(bool flag); - /// Has this contact been disabled? - bool IsEnabled() const; + /// Has this contact been disabled? + bool IsEnabled() const; - /// Get the next contact in the world's contact list. - b2Contact* GetNext(); - const b2Contact* GetNext() const; + /// Get the next contact in the world's contact list. + b2Contact* GetNext(); + const b2Contact* GetNext() const; - /// Get fixture A in this contact. - b2Fixture* GetFixtureA(); - const b2Fixture* GetFixtureA() const; + /// Get fixture A in this contact. + b2Fixture* GetFixtureA(); + const b2Fixture* GetFixtureA() const; - /// Get the child primitive index for fixture A. - int32 GetChildIndexA() const; + /// Get the child primitive index for fixture A. + int32 GetChildIndexA() const; - /// Get fixture B in this contact. - b2Fixture* GetFixtureB(); - const b2Fixture* GetFixtureB() const; + /// Get fixture B in this contact. + b2Fixture* GetFixtureB(); + const b2Fixture* GetFixtureB() const; - /// Get the child primitive index for fixture B. - int32 GetChildIndexB() const; + /// Get the child primitive index for fixture B. + int32 GetChildIndexB() const; - /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. - /// This value persists until set or reset. - void SetFriction(float32 friction); + /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. + /// This value persists until set or reset. + void SetFriction(float32 friction); - /// Get the friction. - float32 GetFriction() const; + /// Get the friction. + float32 GetFriction() const; - /// Reset the friction mixture to the default value. - void ResetFriction(); + /// Reset the friction mixture to the default value. + void ResetFriction(); - /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. - /// The value persists until you set or reset. - void SetRestitution(float32 restitution); + /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. + /// The value persists until you set or reset. + void SetRestitution(float32 restitution); - /// Get the restitution. - float32 GetRestitution() const; + /// Get the restitution. + float32 GetRestitution() const; - /// Reset the restitution to the default value. - void ResetRestitution(); + /// Reset the restitution to the default value. + void ResetRestitution(); - /// Evaluate this contact with your own manifold and transforms. - virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; + /// Set the desired tangent speed for a conveyor belt behavior. In meters per second. + void SetTangentSpeed(float32 speed); + + /// Get the desired tangent speed. In meters per second. + float32 GetTangentSpeed() const; + + /// Evaluate this contact with your own manifold and transforms. + virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; protected: - friend class b2ContactManager; - friend class b2World; - friend class b2ContactSolver; - friend class b2Body; - friend class b2Fixture; + friend class b2ContactManager; + friend class b2World; + friend class b2ContactSolver; + friend class b2Body; + friend class b2Fixture; - // Flags stored in m_flags - enum - { - // Used when crawling contact graph when forming islands. - e_islandFlag = 0x0001, + // Flags stored in m_flags + enum + { + // Used when crawling contact graph when forming islands. + e_islandFlag = 0x0001, // Set when the shapes are touching. - e_touchingFlag = 0x0002, + e_touchingFlag = 0x0002, - // This contact can be disabled (by user) - e_enabledFlag = 0x0004, + // This contact can be disabled (by user) + e_enabledFlag = 0x0004, - // This contact needs filtering because a fixture filter was changed. - e_filterFlag = 0x0008, + // This contact needs filtering because a fixture filter was changed. + e_filterFlag = 0x0008, - // This bullet contact had a TOI event - e_bulletHitFlag = 0x0010, + // This bullet contact had a TOI event + e_bulletHitFlag = 0x0010, - // This contact has a valid TOI in m_toi - e_toiFlag = 0x0020 - }; + // This contact has a valid TOI in m_toi + e_toiFlag = 0x0020 + }; - /// Flag this contact for filtering. Filtering will occur the next time step. - void FlagForFiltering(); + /// Flag this contact for filtering. Filtering will occur the next time step. + void FlagForFiltering(); - static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, - b2Shape::Type typeA, b2Shape::Type typeB); - static void InitializeRegisters(); - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, + b2Shape::Type typeA, b2Shape::Type typeB); + static void InitializeRegisters(); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} - b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - virtual ~b2Contact() {} + b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} + b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); + virtual ~b2Contact() {} - void Update(b2ContactListener* listener); + void Update(b2ContactListener* listener); - static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; - static bool s_initialized; + static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; + static bool s_initialized; - uint32 m_flags; + uint32 m_flags; - // World pool and list pointers. - b2Contact* m_prev; - b2Contact* m_next; + // World pool and list pointers. + b2Contact* m_prev; + b2Contact* m_next; - // Nodes for connecting bodies. - b2ContactEdge m_nodeA; - b2ContactEdge m_nodeB; + // Nodes for connecting bodies. + b2ContactEdge m_nodeA; + b2ContactEdge m_nodeB; - b2Fixture* m_fixtureA; - b2Fixture* m_fixtureB; + b2Fixture* m_fixtureA; + b2Fixture* m_fixtureB; - int32 m_indexA; - int32 m_indexB; + int32 m_indexA; + int32 m_indexB; - b2Manifold m_manifold; + b2Manifold m_manifold; - int32 m_toiCount; - float32 m_toi; + int32 m_toiCount; + float32 m_toi; - float32 m_friction; - float32 m_restitution; + float32 m_friction; + float32 m_restitution; + + float32 m_tangentSpeed; }; inline b2Manifold* b2Contact::GetManifold() { - return &m_manifold; + return &m_manifold; } inline const b2Manifold* b2Contact::GetManifold() const { - return &m_manifold; + return &m_manifold; } inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const { - const b2Body* bodyA = m_fixtureA->GetBody(); - const b2Body* bodyB = m_fixtureB->GetBody(); - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); + const b2Body* bodyA = m_fixtureA->GetBody(); + const b2Body* bodyB = m_fixtureB->GetBody(); + const b2Shape* shapeA = m_fixtureA->GetShape(); + const b2Shape* shapeB = m_fixtureB->GetShape(); - worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); + worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); } inline void b2Contact::SetEnabled(bool flag) { - if (flag) - { - m_flags |= e_enabledFlag; - } - else - { - m_flags &= ~e_enabledFlag; - } + if (flag) + { + m_flags |= e_enabledFlag; + } + else + { + m_flags &= ~e_enabledFlag; + } } inline bool b2Contact::IsEnabled() const { - return (m_flags & e_enabledFlag) == e_enabledFlag; + return (m_flags & e_enabledFlag) == e_enabledFlag; } inline bool b2Contact::IsTouching() const { - return (m_flags & e_touchingFlag) == e_touchingFlag; + return (m_flags & e_touchingFlag) == e_touchingFlag; } inline b2Contact* b2Contact::GetNext() { - return m_next; + return m_next; } inline const b2Contact* b2Contact::GetNext() const { - return m_next; + return m_next; } inline b2Fixture* b2Contact::GetFixtureA() { - return m_fixtureA; + return m_fixtureA; } inline const b2Fixture* b2Contact::GetFixtureA() const { - return m_fixtureA; + return m_fixtureA; } inline b2Fixture* b2Contact::GetFixtureB() { - return m_fixtureB; + return m_fixtureB; } inline int32 b2Contact::GetChildIndexA() const { - return m_indexA; + return m_indexA; } inline const b2Fixture* b2Contact::GetFixtureB() const { - return m_fixtureB; + return m_fixtureB; } inline int32 b2Contact::GetChildIndexB() const { - return m_indexB; + return m_indexB; } inline void b2Contact::FlagForFiltering() { - m_flags |= e_filterFlag; + m_flags |= e_filterFlag; } inline void b2Contact::SetFriction(float32 friction) { - m_friction = friction; + m_friction = friction; } inline float32 b2Contact::GetFriction() const { - return m_friction; + return m_friction; } inline void b2Contact::ResetFriction() { - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); + m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); } inline void b2Contact::SetRestitution(float32 restitution) { - m_restitution = restitution; + m_restitution = restitution; } inline float32 b2Contact::GetRestitution() const { - return m_restitution; + return m_restitution; } inline void b2Contact::ResetRestitution() { - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); + m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); +} + +inline void b2Contact::SetTangentSpeed(float32 speed) +{ + m_tangentSpeed = speed; +} + +inline float32 b2Contact::GetTangentSpeed() const +{ + return m_tangentSpeed; } #endif diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp index 0dc740342a..8224fdc2db 100644 --- a/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp +++ b/external/Box2D/Dynamics/Contacts/b2ContactSolver.cpp @@ -28,805 +28,806 @@ struct b2ContactPositionConstraint { - b2Vec2 localPoints[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - b2Vec2 localCenterA, localCenterB; - float32 invIA, invIB; - b2Manifold::Type type; - float32 radiusA, radiusB; - int32 pointCount; + b2Vec2 localPoints[b2_maxManifoldPoints]; + b2Vec2 localNormal; + b2Vec2 localPoint; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + b2Vec2 localCenterA, localCenterB; + float32 invIA, invIB; + b2Manifold::Type type; + float32 radiusA, radiusB; + int32 pointCount; }; b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) { - m_step = def->step; - m_allocator = def->allocator; - m_count = def->count; - m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); - m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); - m_positions = def->positions; - m_velocities = def->velocities; - m_contacts = def->contacts; + m_step = def->step; + m_allocator = def->allocator; + m_count = def->count; + m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); + m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); + m_positions = def->positions; + m_velocities = def->velocities; + m_contacts = def->contacts; - // Initialize position independent portions of the constraints. - for (int32 i = 0; i < m_count; ++i) - { - b2Contact* contact = m_contacts[i]; + // Initialize position independent portions of the constraints. + for (int32 i = 0; i < m_count; ++i) + { + b2Contact* contact = m_contacts[i]; - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - b2Shape* shapeA = fixtureA->GetShape(); - b2Shape* shapeB = fixtureB->GetShape(); - float32 radiusA = shapeA->m_radius; - float32 radiusB = shapeB->m_radius; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - b2Manifold* manifold = contact->GetManifold(); + b2Fixture* fixtureA = contact->m_fixtureA; + b2Fixture* fixtureB = contact->m_fixtureB; + b2Shape* shapeA = fixtureA->GetShape(); + b2Shape* shapeB = fixtureB->GetShape(); + float32 radiusA = shapeA->m_radius; + float32 radiusB = shapeB->m_radius; + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + b2Manifold* manifold = contact->GetManifold(); - int32 pointCount = manifold->pointCount; - b2Assert(pointCount > 0); + int32 pointCount = manifold->pointCount; + b2Assert(pointCount > 0); - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - vc->friction = contact->m_friction; - vc->restitution = contact->m_restitution; - vc->indexA = bodyA->m_islandIndex; - vc->indexB = bodyB->m_islandIndex; - vc->invMassA = bodyA->m_invMass; - vc->invMassB = bodyB->m_invMass; - vc->invIA = bodyA->m_invI; - vc->invIB = bodyB->m_invI; - vc->contactIndex = i; - vc->pointCount = pointCount; - vc->K.SetZero(); - vc->normalMass.SetZero(); + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + vc->friction = contact->m_friction; + vc->restitution = contact->m_restitution; + vc->tangentSpeed = contact->m_tangentSpeed; + vc->indexA = bodyA->m_islandIndex; + vc->indexB = bodyB->m_islandIndex; + vc->invMassA = bodyA->m_invMass; + vc->invMassB = bodyB->m_invMass; + vc->invIA = bodyA->m_invI; + vc->invIB = bodyB->m_invI; + vc->contactIndex = i; + vc->pointCount = pointCount; + vc->K.SetZero(); + vc->normalMass.SetZero(); - b2ContactPositionConstraint* pc = m_positionConstraints + i; - pc->indexA = bodyA->m_islandIndex; - pc->indexB = bodyB->m_islandIndex; - pc->invMassA = bodyA->m_invMass; - pc->invMassB = bodyB->m_invMass; - pc->localCenterA = bodyA->m_sweep.localCenter; - pc->localCenterB = bodyB->m_sweep.localCenter; - pc->invIA = bodyA->m_invI; - pc->invIB = bodyB->m_invI; - pc->localNormal = manifold->localNormal; - pc->localPoint = manifold->localPoint; - pc->pointCount = pointCount; - pc->radiusA = radiusA; - pc->radiusB = radiusB; - pc->type = manifold->type; + b2ContactPositionConstraint* pc = m_positionConstraints + i; + pc->indexA = bodyA->m_islandIndex; + pc->indexB = bodyB->m_islandIndex; + pc->invMassA = bodyA->m_invMass; + pc->invMassB = bodyB->m_invMass; + pc->localCenterA = bodyA->m_sweep.localCenter; + pc->localCenterB = bodyB->m_sweep.localCenter; + pc->invIA = bodyA->m_invI; + pc->invIB = bodyB->m_invI; + pc->localNormal = manifold->localNormal; + pc->localPoint = manifold->localPoint; + pc->pointCount = pointCount; + pc->radiusA = radiusA; + pc->radiusB = radiusB; + pc->type = manifold->type; - for (int32 j = 0; j < pointCount; ++j) - { - b2ManifoldPoint* cp = manifold->points + j; - b2VelocityConstraintPoint* vcp = vc->points + j; - - if (m_step.warmStarting) - { - vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; - vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; - } - else - { - vcp->normalImpulse = 0.0f; - vcp->tangentImpulse = 0.0f; - } + for (int32 j = 0; j < pointCount; ++j) + { + b2ManifoldPoint* cp = manifold->points + j; + b2VelocityConstraintPoint* vcp = vc->points + j; + + if (m_step.warmStarting) + { + vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; + vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; + } + else + { + vcp->normalImpulse = 0.0f; + vcp->tangentImpulse = 0.0f; + } - vcp->rA.SetZero(); - vcp->rB.SetZero(); - vcp->normalMass = 0.0f; - vcp->tangentMass = 0.0f; - vcp->velocityBias = 0.0f; + vcp->rA.SetZero(); + vcp->rB.SetZero(); + vcp->normalMass = 0.0f; + vcp->tangentMass = 0.0f; + vcp->velocityBias = 0.0f; - pc->localPoints[j] = cp->localPoint; - } - } + pc->localPoints[j] = cp->localPoint; + } + } } b2ContactSolver::~b2ContactSolver() { - m_allocator->Free(m_velocityConstraints); - m_allocator->Free(m_positionConstraints); + m_allocator->Free(m_velocityConstraints); + m_allocator->Free(m_positionConstraints); } // Initialize position dependent portions of the velocity constraints. void b2ContactSolver::InitializeVelocityConstraints() { - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2ContactPositionConstraint* pc = m_positionConstraints + i; + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2ContactPositionConstraint* pc = m_positionConstraints + i; - float32 radiusA = pc->radiusA; - float32 radiusB = pc->radiusB; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + float32 radiusA = pc->radiusA; + float32 radiusB = pc->radiusB; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 mB = vc->invMassB; - float32 iA = vc->invIA; - float32 iB = vc->invIB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; + float32 mA = vc->invMassA; + float32 mB = vc->invMassB; + float32 iA = vc->invIA; + float32 iB = vc->invIB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; - b2Assert(manifold->pointCount > 0); + b2Assert(manifold->pointCount > 0); - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); - b2WorldManifold worldManifold; - worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); + b2WorldManifold worldManifold; + worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); - vc->normal = worldManifold.normal; + vc->normal = worldManifold.normal; - int32 pointCount = vc->pointCount; - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; + int32 pointCount = vc->pointCount; + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; - vcp->rA = worldManifold.points[j] - cA; - vcp->rB = worldManifold.points[j] - cB; + vcp->rA = worldManifold.points[j] - cA; + vcp->rB = worldManifold.points[j] - cB; - float32 rnA = b2Cross(vcp->rA, vc->normal); - float32 rnB = b2Cross(vcp->rB, vc->normal); + float32 rnA = b2Cross(vcp->rA, vc->normal); + float32 rnB = b2Cross(vcp->rB, vc->normal); - float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; + vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - b2Vec2 tangent = b2Cross(vc->normal, 1.0f); + b2Vec2 tangent = b2Cross(vc->normal, 1.0f); - float32 rtA = b2Cross(vcp->rA, tangent); - float32 rtB = b2Cross(vcp->rB, tangent); + float32 rtA = b2Cross(vcp->rA, tangent); + float32 rtB = b2Cross(vcp->rB, tangent); - float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; + float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; + vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; - // Setup a velocity bias for restitution. - vcp->velocityBias = 0.0f; - float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); - if (vRel < -b2_velocityThreshold) - { - vcp->velocityBias = -vc->restitution * vRel; - } - } + // Setup a velocity bias for restitution. + vcp->velocityBias = 0.0f; + float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); + if (vRel < -b2_velocityThreshold) + { + vcp->velocityBias = -vc->restitution * vRel; + } + } - // If we have two points, then prepare the block solver. - if (vc->pointCount == 2) - { - b2VelocityConstraintPoint* vcp1 = vc->points + 0; - b2VelocityConstraintPoint* vcp2 = vc->points + 1; + // If we have two points, then prepare the block solver. + if (vc->pointCount == 2) + { + b2VelocityConstraintPoint* vcp1 = vc->points + 0; + b2VelocityConstraintPoint* vcp2 = vc->points + 1; - float32 rn1A = b2Cross(vcp1->rA, vc->normal); - float32 rn1B = b2Cross(vcp1->rB, vc->normal); - float32 rn2A = b2Cross(vcp2->rA, vc->normal); - float32 rn2B = b2Cross(vcp2->rB, vc->normal); + float32 rn1A = b2Cross(vcp1->rA, vc->normal); + float32 rn1B = b2Cross(vcp1->rB, vc->normal); + float32 rn2A = b2Cross(vcp2->rA, vc->normal); + float32 rn2B = b2Cross(vcp2->rB, vc->normal); - float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; - float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; - float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; + float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; + float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; + float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; - // Ensure a reasonable condition number. - const float32 k_maxConditionNumber = 1000.0f; - if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) - { - // K is safe to invert. - vc->K.ex.Set(k11, k12); - vc->K.ey.Set(k12, k22); - vc->normalMass = vc->K.GetInverse(); - } - else - { - // The constraints are redundant, just use one. - // TODO_ERIN use deepest? - vc->pointCount = 1; - } - } - } + // Ensure a reasonable condition number. + const float32 k_maxConditionNumber = 1000.0f; + if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) + { + // K is safe to invert. + vc->K.ex.Set(k11, k12); + vc->K.ey.Set(k12, k22); + vc->normalMass = vc->K.GetInverse(); + } + else + { + // The constraints are redundant, just use one. + // TODO_ERIN use deepest? + vc->pointCount = 1; + } + } + } } void b2ContactSolver::WarmStart() { - // Warm start. - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + // Warm start. + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; - wA -= iA * b2Cross(vcp->rA, P); - vA -= mA * P; - wB += iB * b2Cross(vcp->rB, P); - vB += mB * P; - } + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; + b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; + wA -= iA * b2Cross(vcp->rA, P); + vA -= mA * P; + wB += iB * b2Cross(vcp->rB, P); + vB += mB * P; + } - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } } void b2ContactSolver::SolveVelocityConstraints() { - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; + int32 indexA = vc->indexA; + int32 indexB = vc->indexB; + float32 mA = vc->invMassA; + float32 iA = vc->invIA; + float32 mB = vc->invMassB; + float32 iB = vc->invIB; + int32 pointCount = vc->pointCount; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; + b2Vec2 vA = m_velocities[indexA].v; + float32 wA = m_velocities[indexA].w; + b2Vec2 vB = m_velocities[indexB].v; + float32 wB = m_velocities[indexB].w; - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = vc->friction; + b2Vec2 normal = vc->normal; + b2Vec2 tangent = b2Cross(normal, 1.0f); + float32 friction = vc->friction; - b2Assert(pointCount == 1 || pointCount == 2); + b2Assert(pointCount == 1 || pointCount == 2); - // Solve tangent constraints first because non-penetration is more important - // than friction. - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; + // Solve tangent constraints first because non-penetration is more important + // than friction. + for (int32 j = 0; j < pointCount; ++j) + { + b2VelocityConstraintPoint* vcp = vc->points + j; - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - // Compute tangent force - float32 vt = b2Dot(dv, tangent); - float32 lambda = vcp->tangentMass * (-vt); + // Compute tangent force + float32 vt = b2Dot(dv, tangent) - vc->tangentSpeed; + float32 lambda = vcp->tangentMass * (-vt); - // b2Clamp the accumulated force - float32 maxFriction = friction * vcp->normalImpulse; - float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - vcp->tangentImpulse; - vcp->tangentImpulse = newImpulse; + // b2Clamp the accumulated force + float32 maxFriction = friction * vcp->normalImpulse; + float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); + lambda = newImpulse - vcp->tangentImpulse; + vcp->tangentImpulse = newImpulse; - // Apply contact impulse - b2Vec2 P = lambda * tangent; + // Apply contact impulse + b2Vec2 P = lambda * tangent; - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } - // Solve normal constraints - if (vc->pointCount == 1) - { - b2VelocityConstraintPoint* vcp = vc->points + 0; + // Solve normal constraints + if (vc->pointCount == 1) + { + b2VelocityConstraintPoint* vcp = vc->points + 0; - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); + // Relative velocity at contact + b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - // Compute normal impulse - float32 vn = b2Dot(dv, normal); - float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); + // Compute normal impulse + float32 vn = b2Dot(dv, normal); + float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); - // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - vcp->normalImpulse; - vcp->normalImpulse = newImpulse; + // b2Clamp the accumulated impulse + float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); + lambda = newImpulse - vcp->normalImpulse; + vcp->normalImpulse = newImpulse; - // Apply contact impulse - b2Vec2 P = lambda * normal; - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); + // Apply contact impulse + b2Vec2 P = lambda * normal; + vA -= mA * P; + wA -= iA * b2Cross(vcp->rA, P); - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - else - { - // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). - // Build the mini LCP for this contact patch - // - // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 - // - // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) - // b = vn0 - velocityBias - // - // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i - // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases - // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid - // solution that satisfies the problem is chosen. - // - // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires - // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). - // - // Substitute: - // - // x = a + d - // - // a := old total impulse - // x := new total impulse - // d := incremental impulse - // - // For the current iteration we extend the formula for the incremental impulse - // to compute the new total impulse: - // - // vn = A * d + b - // = A * (x - a) + b - // = A * x + b - A * a - // = A * x + b' - // b' = b - A * a; + vB += mB * P; + wB += iB * b2Cross(vcp->rB, P); + } + else + { + // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). + // Build the mini LCP for this contact patch + // + // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 + // + // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) + // b = vn0 - velocityBias + // + // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i + // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases + // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid + // solution that satisfies the problem is chosen. + // + // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires + // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). + // + // Substitute: + // + // x = a + d + // + // a := old total impulse + // x := new total impulse + // d := incremental impulse + // + // For the current iteration we extend the formula for the incremental impulse + // to compute the new total impulse: + // + // vn = A * d + b + // = A * (x - a) + b + // = A * x + b - A * a + // = A * x + b' + // b' = b - A * a; - b2VelocityConstraintPoint* cp1 = vc->points + 0; - b2VelocityConstraintPoint* cp2 = vc->points + 1; + b2VelocityConstraintPoint* cp1 = vc->points + 0; + b2VelocityConstraintPoint* cp2 = vc->points + 1; - b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); - b2Assert(a.x >= 0.0f && a.y >= 0.0f); + b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); + b2Assert(a.x >= 0.0f && a.y >= 0.0f); - // Relative velocity at contact - b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + // Relative velocity at contact + b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - // Compute normal velocity - float32 vn1 = b2Dot(dv1, normal); - float32 vn2 = b2Dot(dv2, normal); + // Compute normal velocity + float32 vn1 = b2Dot(dv1, normal); + float32 vn2 = b2Dot(dv2, normal); - b2Vec2 b; - b.x = vn1 - cp1->velocityBias; - b.y = vn2 - cp2->velocityBias; + b2Vec2 b; + b.x = vn1 - cp1->velocityBias; + b.y = vn2 - cp2->velocityBias; - // Compute b' - b -= b2Mul(vc->K, a); + // Compute b' + b -= b2Mul(vc->K, a); - const float32 k_errorTol = 1e-3f; - B2_NOT_USED(k_errorTol); + const float32 k_errorTol = 1e-3f; + B2_NOT_USED(k_errorTol); - for (;;) - { - // - // Case 1: vn = 0 - // - // 0 = A * x + b' - // - // Solve for x: - // - // x = - inv(A) * b' - // - b2Vec2 x = - b2Mul(vc->normalMass, b); + for (;;) + { + // + // Case 1: vn = 0 + // + // 0 = A * x + b' + // + // Solve for x: + // + // x = - inv(A) * b' + // + b2Vec2 x = - b2Mul(vc->normalMass, b); - if (x.x >= 0.0f && x.y >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; + if (x.x >= 0.0f && x.y >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - vn2 = b2Dot(dv2, normal); + // Compute normal velocity + vn1 = b2Dot(dv1, normal); + vn2 = b2Dot(dv2, normal); - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif - break; - } + break; + } - // - // Case 2: vn1 = 0 and x2 = 0 - // - // 0 = a11 * x1 + a12 * 0 + b1' - // vn2 = a21 * x1 + a22 * 0 + b2' - // - x.x = - cp1->normalMass * b.x; - x.y = 0.0f; - vn1 = 0.0f; - vn2 = vc->K.ex.y * x.x + b.y; + // + // Case 2: vn1 = 0 and x2 = 0 + // + // 0 = a11 * x1 + a12 * 0 + b1' + // vn2 = a21 * x1 + a22 * 0 + b2' + // + x.x = - cp1->normalMass * b.x; + x.y = 0.0f; + vn1 = 0.0f; + vn2 = vc->K.ex.y * x.x + b.y; - if (x.x >= 0.0f && vn2 >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; + if (x.x >= 0.0f && vn2 >= 0.0f) + { + // Get the incremental impulse + b2Vec2 d = x - a; - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); + // Postconditions + dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - // Compute normal velocity - vn1 = b2Dot(dv1, normal); + // Compute normal velocity + vn1 = b2Dot(dv1, normal); - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); #endif - break; - } + break; + } - // - // Case 3: vn2 = 0 and x1 = 0 - // - // vn1 = a11 * 0 + a12 * x2 + b1' - // 0 = a21 * 0 + a22 * x2 + b2' - // - x.x = 0.0f; - x.y = - cp2->normalMass * b.y; - vn1 = vc->K.ey.x * x.y + b.x; - vn2 = 0.0f; + // + // Case 3: vn2 = 0 and x1 = 0 + // + // vn1 = a11 * 0 + a12 * x2 + b1' + // 0 = a21 * 0 + a22 * x2 + b2' + // + x.x = 0.0f; + x.y = - cp2->normalMass * b.y; + vn1 = vc->K.ey.x * x.y + b.x; + vn2 = 0.0f; - if (x.y >= 0.0f && vn1 >= 0.0f) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; + if (x.y >= 0.0f && vn1 >= 0.0f) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 - // Postconditions - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); + // Postconditions + dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - // Compute normal velocity - vn2 = b2Dot(dv2, normal); + // Compute normal velocity + vn2 = b2Dot(dv2, normal); - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); + b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif - break; - } + break; + } - // - // Case 4: x1 = 0 and x2 = 0 - // - // vn1 = b1 - // vn2 = b2; - x.x = 0.0f; - x.y = 0.0f; - vn1 = b.x; - vn2 = b.y; + // + // Case 4: x1 = 0 and x2 = 0 + // + // vn1 = b1 + // vn2 = b2; + x.x = 0.0f; + x.y = 0.0f; + vn1 = b.x; + vn2 = b.y; - if (vn1 >= 0.0f && vn2 >= 0.0f ) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; + if (vn1 >= 0.0f && vn2 >= 0.0f ) + { + // Resubstitute for the incremental impulse + b2Vec2 d = x - a; - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); + // Apply incremental impulse + b2Vec2 P1 = d.x * normal; + b2Vec2 P2 = d.y * normal; + vA -= mA * (P1 + P2); + wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); + vB += mB * (P1 + P2); + wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; + // Accumulate + cp1->normalImpulse = x.x; + cp2->normalImpulse = x.y; - break; - } + break; + } - // No solution, give up. This is hit sometimes, but it doesn't seem to matter. - break; - } - } + // No solution, give up. This is hit sometimes, but it doesn't seem to matter. + break; + } + } - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } + m_velocities[indexA].v = vA; + m_velocities[indexA].w = wA; + m_velocities[indexB].v = vB; + m_velocities[indexB].w = wB; + } } void b2ContactSolver::StoreImpulses() { - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); + for (int32 i = 0; i < m_count; ++i) + { + b2ContactVelocityConstraint* vc = m_velocityConstraints + i; + b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - for (int32 j = 0; j < vc->pointCount; ++j) - { - manifold->points[j].normalImpulse = vc->points[j].normalImpulse; - manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; - } - } + for (int32 j = 0; j < vc->pointCount; ++j) + { + manifold->points[j].normalImpulse = vc->points[j].normalImpulse; + manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; + } + } } struct b2PositionSolverManifold { - void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) - { - b2Assert(pc->pointCount > 0); + void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) + { + b2Assert(pc->pointCount > 0); - switch (pc->type) - { - case b2Manifold::e_circles: - { - b2Vec2 pointA = b2Mul(xfA, pc->localPoint); - b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); - normal = pointB - pointA; - normal.Normalize(); - point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; - } - break; + switch (pc->type) + { + case b2Manifold::e_circles: + { + b2Vec2 pointA = b2Mul(xfA, pc->localPoint); + b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); + normal = pointB - pointA; + normal.Normalize(); + point = 0.5f * (pointA + pointB); + separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; + } + break; - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); + case b2Manifold::e_faceA: + { + normal = b2Mul(xfA.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); - b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - } - break; + b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; + } + break; - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); + case b2Manifold::e_faceB: + { + normal = b2Mul(xfB.q, pc->localNormal); + b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); - b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; + b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); + separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; + point = clipPoint; - // Ensure normal points from A to B - normal = -normal; - } - break; - } - } + // Ensure normal points from A to B + normal = -normal; + } + break; + } + } - b2Vec2 normal; - b2Vec2 point; - float32 separation; + b2Vec2 normal; + b2Vec2 point; + float32 separation; }; // Sequential solver. bool b2ContactSolver::SolvePositionConstraints() { - float32 minSeparation = 0.0f; + float32 minSeparation = 0.0f; - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - float32 mA = pc->invMassA; - float32 iA = pc->invIA; - b2Vec2 localCenterB = pc->localCenterB; - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - int32 pointCount = pc->pointCount; + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + float32 mA = pc->invMassA; + float32 iA = pc->invIA; + b2Vec2 localCenterB = pc->localCenterB; + float32 mB = pc->invMassB; + float32 iB = pc->invIB; + int32 pointCount = pc->pointCount; - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; - b2Vec2 point = psm.point; - float32 separation = psm.separation; + b2Vec2 point = psm.point; + float32 separation = psm.separation; - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; - b2Vec2 P = impulse * normal; + b2Vec2 P = impulse * normal; - cA -= mA * P; - aA -= iA * b2Cross(rA, P); + cA -= mA * P; + aA -= iA * b2Cross(rA, P); - cB += mB * P; - aB += iB * b2Cross(rB, P); - } + cB += mB * P; + aB += iB * b2Cross(rB, P); + } - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -3.0f * b2_linearSlop; + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -3.0f * b2_linearSlop; } // Sequential position solver for position constraints. bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) { - float32 minSeparation = 0.0f; + float32 minSeparation = 0.0f; - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; + for (int32 i = 0; i < m_count; ++i) + { + b2ContactPositionConstraint* pc = m_positionConstraints + i; - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - int32 pointCount = pc->pointCount; + int32 indexA = pc->indexA; + int32 indexB = pc->indexB; + b2Vec2 localCenterA = pc->localCenterA; + b2Vec2 localCenterB = pc->localCenterB; + int32 pointCount = pc->pointCount; - float32 mA = 0.0f; - float32 iA = 0.0f; - if (indexA == toiIndexA || indexA == toiIndexB) - { - mA = pc->invMassA; - iA = pc->invIA; - } + float32 mA = 0.0f; + float32 iA = 0.0f; + if (indexA == toiIndexA || indexA == toiIndexB) + { + mA = pc->invMassA; + iA = pc->invIA; + } - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - if (indexB == toiIndexA || indexB == toiIndexB) - { - mB = pc->invMassB; - iB = pc->invIB; - } + float32 mB = 0.0f; + float32 iB = 0.; + if (indexB == toiIndexA || indexB == toiIndexB) + { + mB = pc->invMassB; + iB = pc->invIB; + } - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; + b2Vec2 cA = m_positions[indexA].c; + float32 aA = m_positions[indexA].a; - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; + b2Vec2 cB = m_positions[indexB].c; + float32 aB = m_positions[indexB].a; - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); + // Solve normal constraints + for (int32 j = 0; j < pointCount; ++j) + { + b2Transform xfA, xfB; + xfA.q.Set(aA); + xfB.q.Set(aB); + xfA.p = cA - b2Mul(xfA.q, localCenterA); + xfB.p = cB - b2Mul(xfB.q, localCenterB); - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; + b2PositionSolverManifold psm; + psm.Initialize(pc, xfA, xfB, j); + b2Vec2 normal = psm.normal; - b2Vec2 point = psm.point; - float32 separation = psm.separation; + b2Vec2 point = psm.point; + float32 separation = psm.separation; - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; + b2Vec2 rA = point - cA; + b2Vec2 rB = point - cB; - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); + // Track max constraint error. + minSeparation = b2Min(minSeparation, separation); - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); + // Prevent large corrections and allow slop. + float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; + // Compute the effective mass. + float32 rnA = b2Cross(rA, normal); + float32 rnB = b2Cross(rB, normal); + float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; + // Compute normal impulse + float32 impulse = K > 0.0f ? - C / K : 0.0f; - b2Vec2 P = impulse * normal; + b2Vec2 P = impulse * normal; - cA -= mA * P; - aA -= iA * b2Cross(rA, P); + cA -= mA * P; + aA -= iA * b2Cross(rA, P); - cB += mB * P; - aB += iB * b2Cross(rB, P); - } + cB += mB * P; + aB += iB * b2Cross(rB, P); + } - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; + m_positions[indexA].c = cA; + m_positions[indexA].a = aA; - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } + m_positions[indexB].c = cB; + m_positions[indexB].a = aB; + } - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; + // We can't expect minSpeparation >= -b2_linearSlop because we don't + // push the separation above -b2_linearSlop. + return minSeparation >= -1.5f * b2_linearSlop; } diff --git a/external/Box2D/Dynamics/Contacts/b2ContactSolver.h b/external/Box2D/Dynamics/Contacts/b2ContactSolver.h index aef1987a9e..a622e30d83 100644 --- a/external/Box2D/Dynamics/Contacts/b2ContactSolver.h +++ b/external/Box2D/Dynamics/Contacts/b2ContactSolver.h @@ -30,64 +30,65 @@ struct b2ContactPositionConstraint; struct b2VelocityConstraintPoint { - b2Vec2 rA; - b2Vec2 rB; - float32 normalImpulse; - float32 tangentImpulse; - float32 normalMass; - float32 tangentMass; - float32 velocityBias; + b2Vec2 rA; + b2Vec2 rB; + float32 normalImpulse; + float32 tangentImpulse; + float32 normalMass; + float32 tangentMass; + float32 velocityBias; }; struct b2ContactVelocityConstraint { - b2VelocityConstraintPoint points[b2_maxManifoldPoints]; - b2Vec2 normal; - b2Mat22 normalMass; - b2Mat22 K; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - float32 invIA, invIB; - float32 friction; - float32 restitution; - int32 pointCount; - int32 contactIndex; + b2VelocityConstraintPoint points[b2_maxManifoldPoints]; + b2Vec2 normal; + b2Mat22 normalMass; + b2Mat22 K; + int32 indexA; + int32 indexB; + float32 invMassA, invMassB; + float32 invIA, invIB; + float32 friction; + float32 restitution; + float32 tangentSpeed; + int32 pointCount; + int32 contactIndex; }; struct b2ContactSolverDef { - b2TimeStep step; - b2Contact** contacts; - int32 count; - b2Position* positions; - b2Velocity* velocities; - b2StackAllocator* allocator; + b2TimeStep step; + b2Contact** contacts; + int32 count; + b2Position* positions; + b2Velocity* velocities; + b2StackAllocator* allocator; }; class b2ContactSolver { public: - b2ContactSolver(b2ContactSolverDef* def); - ~b2ContactSolver(); + b2ContactSolver(b2ContactSolverDef* def); + ~b2ContactSolver(); - void InitializeVelocityConstraints(); + void InitializeVelocityConstraints(); - void WarmStart(); - void SolveVelocityConstraints(); - void StoreImpulses(); + void WarmStart(); + void SolveVelocityConstraints(); + void StoreImpulses(); - bool SolvePositionConstraints(); - bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); + bool SolvePositionConstraints(); + bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); - b2TimeStep m_step; - b2Position* m_positions; - b2Velocity* m_velocities; - b2StackAllocator* m_allocator; - b2ContactPositionConstraint* m_positionConstraints; - b2ContactVelocityConstraint* m_velocityConstraints; - b2Contact** m_contacts; - int m_count; + b2TimeStep m_step; + b2Position* m_positions; + b2Velocity* m_velocities; + b2StackAllocator* m_allocator; + b2ContactPositionConstraint* m_positionConstraints; + b2ContactVelocityConstraint* m_velocityConstraints; + b2Contact** m_contacts; + int m_count; }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp index aade42880a..d1fd3295ce 100644 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp @@ -21,30 +21,29 @@ #include #include -using namespace std; b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); - return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); + void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); + return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); } void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); - allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); + ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); + allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); } b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) : b2Contact(fixtureA, 0, fixtureB, 0) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); } void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2CollideEdgeAndCircle( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); + b2CollideEdgeAndCircle( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h index 70771ec536..e7a34553c1 100644 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2EdgeAndCircleContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndCircleContact() {} + b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndCircleContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp index 04ce394107..ba536bc39d 100644 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp @@ -21,30 +21,29 @@ #include #include -using namespace std; b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); - return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); + void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); + return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); } void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); - allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); + ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); + allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); } b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) : b2Contact(fixtureA, 0, fixtureB, 0) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); } void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2CollideEdgeAndPolygon( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); + b2CollideEdgeAndPolygon( manifold, + (b2EdgeShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h index f65f3acca9..3b40f12163 100644 --- a/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h +++ b/external/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2EdgeAndPolygonContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndPolygonContact() {} + b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2EdgeAndPolygonContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp index 961b26f38a..7c9cbcc926 100644 --- a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp @@ -21,30 +21,29 @@ #include #include -using namespace std; b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); - return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); + void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); + return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); } void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); - allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); + ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); + allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); } b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) : b2Contact(fixtureA, 0, fixtureB, 0) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); } void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2CollidePolygonAndCircle( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); + b2CollidePolygonAndCircle( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2CircleShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h index 7b1a5288b4..fe0645e080 100644 --- a/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h +++ b/external/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h @@ -26,13 +26,13 @@ class b2BlockAllocator; class b2PolygonAndCircleContact : public b2Contact { public: - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonAndCircleContact() {} + b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonAndCircleContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp index a2884a440d..b5706ca104 100644 --- a/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp +++ b/external/Box2D/Dynamics/Contacts/b2PolygonContact.cpp @@ -24,30 +24,29 @@ #include #include -using namespace std; b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) { - void* mem = allocator->Allocate(sizeof(b2PolygonContact)); - return new (mem) b2PolygonContact(fixtureA, fixtureB); + void* mem = allocator->Allocate(sizeof(b2PolygonContact)); + return new (mem) b2PolygonContact(fixtureA, fixtureB); } void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { - ((b2PolygonContact*)contact)->~b2PolygonContact(); - allocator->Free(contact, sizeof(b2PolygonContact)); + ((b2PolygonContact*)contact)->~b2PolygonContact(); + allocator->Free(contact, sizeof(b2PolygonContact)); } b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) + : b2Contact(fixtureA, 0, fixtureB, 0) { - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); + b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); } void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) { - b2CollidePolygons( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); + b2CollidePolygons( manifold, + (b2PolygonShape*)m_fixtureA->GetShape(), xfA, + (b2PolygonShape*)m_fixtureB->GetShape(), xfB); } diff --git a/external/Box2D/Dynamics/Contacts/b2PolygonContact.h b/external/Box2D/Dynamics/Contacts/b2PolygonContact.h index 302684232a..434e6c9266 100644 --- a/external/Box2D/Dynamics/Contacts/b2PolygonContact.h +++ b/external/Box2D/Dynamics/Contacts/b2PolygonContact.h @@ -26,14 +26,14 @@ class b2BlockAllocator; class b2PolygonContact : public b2Contact { public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); + static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, + b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); + static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonContact() {} + b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); + ~b2PolygonContact() {} - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); + void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB); }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp index b2d4bd006c..ba2b6c0099 100644 --- a/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2DistanceJoint.cpp @@ -36,225 +36,225 @@ // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, - const b2Vec2& anchor1, const b2Vec2& anchor2) + const b2Vec2& anchor1, const b2Vec2& anchor2) { - bodyA = b1; - bodyB = b2; - localAnchorA = bodyA->GetLocalPoint(anchor1); - localAnchorB = bodyB->GetLocalPoint(anchor2); - b2Vec2 d = anchor2 - anchor1; - length = d.Length(); + bodyA = b1; + bodyB = b2; + localAnchorA = bodyA->GetLocalPoint(anchor1); + localAnchorB = bodyB->GetLocalPoint(anchor2); + b2Vec2 d = anchor2 - anchor1; + length = d.Length(); } b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_length = def->length; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - m_impulse = 0.0f; - m_gamma = 0.0f; - m_bias = 0.0f; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_length = def->length; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; + m_impulse = 0.0f; + m_gamma = 0.0f; + m_bias = 0.0f; } void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; - // Handle singularity. - float32 length = m_u.Length(); - if (length > b2_linearSlop) - { - m_u *= 1.0f / length; - } - else - { - m_u.Set(0.0f, 0.0f); - } + // Handle singularity. + float32 length = m_u.Length(); + if (length > b2_linearSlop) + { + m_u *= 1.0f / length; + } + else + { + m_u.Set(0.0f, 0.0f); + } - float32 crAu = b2Cross(m_rA, m_u); - float32 crBu = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; + float32 crAu = b2Cross(m_rA, m_u); + float32 crBu = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; - // Compute the effective mass matrix. - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + // Compute the effective mass matrix. + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - if (m_frequencyHz > 0.0f) - { - float32 C = length - m_length; + if (m_frequencyHz > 0.0f) + { + float32 C = length - m_length; - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; - // Damping coefficient - float32 d = 2.0f * m_mass * m_dampingRatio * omega; + // Damping coefficient + float32 d = 2.0f * m_mass * m_dampingRatio * omega; - // Spring stiffness - float32 k = m_mass * omega * omega; + // Spring stiffness + float32 k = m_mass * omega * omega; - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; - invMass += m_gamma; - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - } - else - { - m_gamma = 0.0f; - m_bias = 0.0f; - } + invMass += m_gamma; + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + } + else + { + m_gamma = 0.0f; + m_bias = 0.0f; + } - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 Cdot = b2Dot(m_u, vpB - vpA); + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 Cdot = b2Dot(m_u, vpB - vpA); - float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); - m_impulse += impulse; + float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); + m_impulse += impulse; - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) { - if (m_frequencyHz > 0.0f) - { - // There is no position correction for soft distance constraints. - return true; - } + if (m_frequencyHz > 0.0f) + { + // There is no position correction for soft distance constraints. + return true; + } - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; - float32 length = u.Normalize(); - float32 C = length - m_length; - C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); + float32 length = u.Normalize(); + float32 C = length - m_length; + C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return b2Abs(C) < b2_linearSlop; + return b2Abs(C) < b2_linearSlop; } b2Vec2 b2DistanceJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2DistanceJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; } float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const { - B2_NOT_USED(inv_dt); - return 0.0f; + B2_NOT_USED(inv_dt); + return 0.0f; } void b2DistanceJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2DistanceJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.length = %.15lef;\n", m_length); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2DistanceJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.length = %.15lef;\n", m_length); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2DistanceJoint.h b/external/Box2D/Dynamics/Joints/b2DistanceJoint.h index fc11476ff9..2faba9d479 100644 --- a/external/Box2D/Dynamics/Joints/b2DistanceJoint.h +++ b/external/Box2D/Dynamics/Joints/b2DistanceJoint.h @@ -29,36 +29,36 @@ /// @warning Do not use a zero or short length. struct b2DistanceJointDef : public b2JointDef { - b2DistanceJointDef() - { - type = e_distanceJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - length = 1.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } + b2DistanceJointDef() + { + type = e_distanceJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + length = 1.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } - /// Initialize the bodies, anchors, and length using the world - /// anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& anchorA, const b2Vec2& anchorB); + /// Initialize the bodies, anchors, and length using the world + /// anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& anchorA, const b2Vec2& anchorB); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The natural length between the anchor points. - float32 length; + /// The natural length between the anchor points. + float32 length; - /// The mass-spring-damper frequency in Hertz. A value of 0 - /// disables softness. - float32 frequencyHz; + /// The mass-spring-damper frequency in Hertz. A value of 0 + /// disables softness. + float32 frequencyHz; - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; }; /// A distance joint constrains two points on two bodies @@ -68,102 +68,102 @@ class b2DistanceJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; - /// Get the reaction torque given the inverse time step. - /// Unit is N*m. This is always zero for a distance joint. - float32 GetReactionTorque(float32 inv_dt) const; + /// Get the reaction torque given the inverse time step. + /// Unit is N*m. This is always zero for a distance joint. + float32 GetReactionTorque(float32 inv_dt) const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// Set/get the natural length. - /// Manipulating the length can lead to non-physical behavior when the frequency is zero. - void SetLength(float32 length); - float32 GetLength() const; + /// Set/get the natural length. + /// Manipulating the length can lead to non-physical behavior when the frequency is zero. + void SetLength(float32 length); + float32 GetLength() const; - /// Set/get frequency in Hz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; + /// Set/get frequency in Hz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; - /// Dump joint to dmLog - void Dump(); + /// Dump joint to dmLog + void Dump(); protected: - friend class b2Joint; - b2DistanceJoint(const b2DistanceJointDef* data); + friend class b2Joint; + b2DistanceJoint(const b2DistanceJointDef* data); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_gamma; - float32 m_impulse; - float32 m_length; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_gamma; + float32 m_impulse; + float32 m_length; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; }; inline void b2DistanceJoint::SetLength(float32 length) { - m_length = length; + m_length = length; } inline float32 b2DistanceJoint::GetLength() const { - return m_length; + return m_length; } inline void b2DistanceJoint::SetFrequency(float32 hz) { - m_frequencyHz = hz; + m_frequencyHz = hz; } inline float32 b2DistanceJoint::GetFrequency() const { - return m_frequencyHz; + return m_frequencyHz; } inline void b2DistanceJoint::SetDampingRatio(float32 ratio) { - m_dampingRatio = ratio; + m_dampingRatio = ratio; } inline float32 b2DistanceJoint::GetDampingRatio() const { - return m_dampingRatio; + return m_dampingRatio; } #endif diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp index 6e6018db10..412d257a78 100644 --- a/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2FrictionJoint.cpp @@ -34,218 +34,218 @@ void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); } b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; - m_maxForce = def->maxForce; - m_maxTorque = def->maxTorque; + m_maxForce = def->maxForce; + m_maxTorque = def->maxTorque; } void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - // Compute the effective mass matrix. - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + // Compute the effective mass matrix. + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Mat22 K; - K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; - K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; + b2Mat22 K; + K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; + K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - m_linearMass = K.GetInverse(); + m_linearMass = K.GetInverse(); - m_angularMass = iA + iB; - if (m_angularMass > 0.0f) - { - m_angularMass = 1.0f / m_angularMass; - } + m_angularMass = iA + iB; + if (m_angularMass > 0.0f) + { + m_angularMass = 1.0f / m_angularMass; + } - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_linearImpulse *= data.step.dtRatio; - m_angularImpulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_linearImpulse *= data.step.dtRatio; + m_angularImpulse *= data.step.dtRatio; - b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); - } - else - { - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - } + b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); + } + else + { + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - float32 h = data.step.dt; + float32 h = data.step.dt; - // Solve angular friction - { - float32 Cdot = wB - wA; - float32 impulse = -m_angularMass * Cdot; + // Solve angular friction + { + float32 Cdot = wB - wA; + float32 impulse = -m_angularMass * Cdot; - float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = h * m_maxTorque; - m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_angularImpulse - oldImpulse; + float32 oldImpulse = m_angularImpulse; + float32 maxImpulse = h * m_maxTorque; + m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_angularImpulse - oldImpulse; - wA -= iA * impulse; - wB += iB * impulse; - } + wA -= iA * impulse; + wB += iB * impulse; + } - // Solve linear friction - { - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + // Solve linear friction + { + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); - b2Vec2 oldImpulse = m_linearImpulse; - m_linearImpulse += impulse; + b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); + b2Vec2 oldImpulse = m_linearImpulse; + m_linearImpulse += impulse; - float32 maxImpulse = h * m_maxForce; + float32 maxImpulse = h * m_maxForce; - if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_linearImpulse.Normalize(); - m_linearImpulse *= maxImpulse; - } + if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_linearImpulse.Normalize(); + m_linearImpulse *= maxImpulse; + } - impulse = m_linearImpulse - oldImpulse; + impulse = m_linearImpulse - oldImpulse; - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(data); + B2_NOT_USED(data); - return true; + return true; } b2Vec2 b2FrictionJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2FrictionJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const { - return inv_dt * m_linearImpulse; + return inv_dt * m_linearImpulse; } float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * m_angularImpulse; + return inv_dt * m_angularImpulse; } void b2FrictionJoint::SetMaxForce(float32 force) { - b2Assert(b2IsValid(force) && force >= 0.0f); - m_maxForce = force; + b2Assert(b2IsValid(force) && force >= 0.0f); + m_maxForce = force; } float32 b2FrictionJoint::GetMaxForce() const { - return m_maxForce; + return m_maxForce; } void b2FrictionJoint::SetMaxTorque(float32 torque) { - b2Assert(b2IsValid(torque) && torque >= 0.0f); - m_maxTorque = torque; + b2Assert(b2IsValid(torque) && torque >= 0.0f); + m_maxTorque = torque; } float32 b2FrictionJoint::GetMaxTorque() const { - return m_maxTorque; + return m_maxTorque; } void b2FrictionJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2FrictionJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); - b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2FrictionJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); + b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2FrictionJoint.h b/external/Box2D/Dynamics/Joints/b2FrictionJoint.h index 3ee40c6298..d57abe80d3 100644 --- a/external/Box2D/Dynamics/Joints/b2FrictionJoint.h +++ b/external/Box2D/Dynamics/Joints/b2FrictionJoint.h @@ -24,30 +24,30 @@ /// Friction joint definition. struct b2FrictionJointDef : public b2JointDef { - b2FrictionJointDef() - { - type = e_frictionJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - maxForce = 0.0f; - maxTorque = 0.0f; - } + b2FrictionJointDef() + { + type = e_frictionJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + maxForce = 0.0f; + maxTorque = 0.0f; + } - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The maximum friction force in N. - float32 maxForce; + /// The maximum friction force in N. + float32 maxForce; - /// The maximum friction torque in N-m. - float32 maxTorque; + /// The maximum friction torque in N-m. + float32 maxTorque; }; /// Friction joint. This is used for top-down friction. @@ -55,65 +55,65 @@ struct b2FrictionJointDef : public b2JointDef class b2FrictionJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// Set the maximum friction force in N. - void SetMaxForce(float32 force); + /// Set the maximum friction force in N. + void SetMaxForce(float32 force); - /// Get the maximum friction force in N. - float32 GetMaxForce() const; + /// Get the maximum friction force in N. + float32 GetMaxForce() const; - /// Set the maximum friction torque in N*m. - void SetMaxTorque(float32 torque); + /// Set the maximum friction torque in N*m. + void SetMaxTorque(float32 torque); - /// Get the maximum friction torque in N*m. - float32 GetMaxTorque() const; + /// Get the maximum friction torque in N*m. + float32 GetMaxTorque() const; - /// Dump joint to dmLog - void Dump(); + /// Dump joint to dmLog + void Dump(); protected: - friend class b2Joint; + friend class b2Joint; - b2FrictionJoint(const b2FrictionJointDef* def); + b2FrictionJoint(const b2FrictionJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; - // Solver shared - b2Vec2 m_linearImpulse; - float32 m_angularImpulse; - float32 m_maxForce; - float32 m_maxTorque; + // Solver shared + b2Vec2 m_linearImpulse; + float32 m_angularImpulse; + float32 m_maxForce; + float32 m_maxTorque; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat22 m_linearMass; - float32 m_angularMass; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat22 m_linearMass; + float32 m_angularMass; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.cpp b/external/Box2D/Dynamics/Joints/b2GearJoint.cpp index 9741cdd5a4..155eb0c1de 100644 --- a/external/Box2D/Dynamics/Joints/b2GearJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2GearJoint.cpp @@ -44,380 +44,376 @@ b2GearJoint::b2GearJoint(const b2GearJointDef* def) : b2Joint(def) { - m_joint1 = def->joint1; - m_joint2 = def->joint2; + m_joint1 = def->joint1; + m_joint2 = def->joint2; - m_typeA = m_joint1->GetType(); - m_typeB = m_joint2->GetType(); + m_typeA = m_joint1->GetType(); + m_typeB = m_joint2->GetType(); - b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); - b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); + b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); + b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); - float32 coordinateA, coordinateB; + float32 coordinateA, coordinateB; - // TODO_ERIN there might be some problem with the joint edges in b2Joint. + // TODO_ERIN there might be some problem with the joint edges in b2Joint. - m_bodyC = m_joint1->GetBodyA(); - m_bodyA = m_joint1->GetBodyB(); + m_bodyC = m_joint1->GetBodyA(); + m_bodyA = m_joint1->GetBodyB(); - // Get geometry of joint1 - b2Transform xfA = m_bodyA->m_xf; - float32 aA = m_bodyA->m_sweep.a; - b2Transform xfC = m_bodyC->m_xf; - float32 aC = m_bodyC->m_sweep.a; + // Get geometry of joint1 + b2Transform xfA = m_bodyA->m_xf; + float32 aA = m_bodyA->m_sweep.a; + b2Transform xfC = m_bodyC->m_xf; + float32 aC = m_bodyC->m_sweep.a; - if (m_typeA == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; - m_localAnchorC = revolute->m_localAnchorA; - m_localAnchorA = revolute->m_localAnchorB; - m_referenceAngleA = revolute->m_referenceAngle; - m_localAxisC.SetZero(); + if (m_typeA == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; + m_localAnchorC = revolute->m_localAnchorA; + m_localAnchorA = revolute->m_localAnchorB; + m_referenceAngleA = revolute->m_referenceAngle; + m_localAxisC.SetZero(); - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; - m_localAnchorC = prismatic->m_localAnchorA; - m_localAnchorA = prismatic->m_localAnchorB; - m_referenceAngleA = prismatic->m_referenceAngle; - m_localAxisC = prismatic->m_localXAxisA; + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; + m_localAnchorC = prismatic->m_localAnchorA; + m_localAnchorA = prismatic->m_localAnchorB; + m_referenceAngleA = prismatic->m_referenceAngle; + m_localAxisC = prismatic->m_localXAxisA; - b2Vec2 pC = m_localAnchorC; - b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } + b2Vec2 pC = m_localAnchorC; + b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } - m_bodyD = m_joint2->GetBodyA(); - m_bodyB = m_joint2->GetBodyB(); + m_bodyD = m_joint2->GetBodyA(); + m_bodyB = m_joint2->GetBodyB(); - // Get geometry of joint2 - b2Transform xfB = m_bodyB->m_xf; - float32 aB = m_bodyB->m_sweep.a; - b2Transform xfD = m_bodyD->m_xf; - float32 aD = m_bodyD->m_sweep.a; + // Get geometry of joint2 + b2Transform xfB = m_bodyB->m_xf; + float32 aB = m_bodyB->m_sweep.a; + b2Transform xfD = m_bodyD->m_xf; + float32 aD = m_bodyD->m_sweep.a; - if (m_typeB == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; - m_localAnchorD = revolute->m_localAnchorA; - m_localAnchorB = revolute->m_localAnchorB; - m_referenceAngleB = revolute->m_referenceAngle; - m_localAxisD.SetZero(); + if (m_typeB == e_revoluteJoint) + { + b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; + m_localAnchorD = revolute->m_localAnchorA; + m_localAnchorB = revolute->m_localAnchorB; + m_referenceAngleB = revolute->m_referenceAngle; + m_localAxisD.SetZero(); - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; - m_localAnchorD = prismatic->m_localAnchorA; - m_localAnchorB = prismatic->m_localAnchorB; - m_referenceAngleB = prismatic->m_referenceAngle; - m_localAxisD = prismatic->m_localXAxisA; + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; + m_localAnchorD = prismatic->m_localAnchorA; + m_localAnchorB = prismatic->m_localAnchorB; + m_referenceAngleB = prismatic->m_referenceAngle; + m_localAxisD = prismatic->m_localXAxisA; - b2Vec2 pD = m_localAnchorD; - b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } + b2Vec2 pD = m_localAnchorD; + b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } - m_ratio = def->ratio; + m_ratio = def->ratio; - m_constant = coordinateA + m_ratio * coordinateB; + m_constant = coordinateA + m_ratio * coordinateB; - m_impulse = 0.0f; + m_impulse = 0.0f; } void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_indexC = m_bodyC->m_islandIndex; - m_indexD = m_bodyD->m_islandIndex; - m_lcA = m_bodyA->m_sweep.localCenter; - m_lcB = m_bodyB->m_sweep.localCenter; - m_lcC = m_bodyC->m_sweep.localCenter; - m_lcD = m_bodyD->m_sweep.localCenter; - m_mA = m_bodyA->m_invMass; - m_mB = m_bodyB->m_invMass; - m_mC = m_bodyC->m_invMass; - m_mD = m_bodyD->m_invMass; - m_iA = m_bodyA->m_invI; - m_iB = m_bodyB->m_invI; - m_iC = m_bodyC->m_invI; - m_iD = m_bodyD->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_indexC = m_bodyC->m_islandIndex; + m_indexD = m_bodyD->m_islandIndex; + m_lcA = m_bodyA->m_sweep.localCenter; + m_lcB = m_bodyB->m_sweep.localCenter; + m_lcC = m_bodyC->m_sweep.localCenter; + m_lcD = m_bodyD->m_sweep.localCenter; + m_mA = m_bodyA->m_invMass; + m_mB = m_bodyB->m_invMass; + m_mC = m_bodyC->m_invMass; + m_mD = m_bodyD->m_invMass; + m_iA = m_bodyA->m_invI; + m_iB = m_bodyB->m_invI; + m_iC = m_bodyC->m_invI; + m_iD = m_bodyD->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; + float32 aC = data.positions[m_indexC].a; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; + float32 aD = data.positions[m_indexD].a; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - m_mass = 0.0f; + m_mass = 0.0f; - if (m_typeA == e_revoluteJoint) - { - m_JvAC.SetZero(); - m_JwA = 1.0f; - m_JwC = 1.0f; - m_mass += m_iA + m_iC; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - m_JvAC = u; - m_JwC = b2Cross(rC, u); - m_JwA = b2Cross(rA, u); - m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; - } + if (m_typeA == e_revoluteJoint) + { + m_JvAC.SetZero(); + m_JwA = 1.0f; + m_JwC = 1.0f; + m_mass += m_iA + m_iC; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + m_JvAC = u; + m_JwC = b2Cross(rC, u); + m_JwA = b2Cross(rA, u); + m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; + } - if (m_typeB == e_revoluteJoint) - { - m_JvBD.SetZero(); - m_JwB = m_ratio; - m_JwD = m_ratio; - m_mass += m_ratio * m_ratio * (m_iB + m_iD); - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - m_JvBD = m_ratio * u; - m_JwD = m_ratio * b2Cross(rD, u); - m_JwB = m_ratio * b2Cross(rB, u); - m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; - } + if (m_typeB == e_revoluteJoint) + { + m_JvBD.SetZero(); + m_JwB = m_ratio; + m_JwD = m_ratio; + m_mass += m_ratio * m_ratio * (m_iB + m_iD); + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + m_JvBD = m_ratio * u; + m_JwD = m_ratio * b2Cross(rD, u); + m_JwB = m_ratio * b2Cross(rB, u); + m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; + } - // Compute effective mass. - m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; + // Compute effective mass. + m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; - if (data.step.warmStarting) - { - vA += (m_mA * m_impulse) * m_JvAC; - wA += m_iA * m_impulse * m_JwA; - vB += (m_mB * m_impulse) * m_JvBD; - wB += m_iB * m_impulse * m_JwB; - vC -= (m_mC * m_impulse) * m_JvAC; - wC -= m_iC * m_impulse * m_JwC; - vD -= (m_mD * m_impulse) * m_JvBD; - wD -= m_iD * m_impulse * m_JwD; - } - else - { - m_impulse = 0.0f; - } + if (data.step.warmStarting) + { + vA += (m_mA * m_impulse) * m_JvAC; + wA += m_iA * m_impulse * m_JwA; + vB += (m_mB * m_impulse) * m_JvBD; + wB += m_iB * m_impulse * m_JwB; + vC -= (m_mC * m_impulse) * m_JvAC; + wC -= m_iC * m_impulse * m_JwC; + vD -= (m_mD * m_impulse) * m_JvBD; + wD -= m_iD * m_impulse * m_JwD; + } + else + { + m_impulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; } void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + b2Vec2 vC = data.velocities[m_indexC].v; + float32 wC = data.velocities[m_indexC].w; + b2Vec2 vD = data.velocities[m_indexD].v; + float32 wD = data.velocities[m_indexD].w; - float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); - Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); + float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); + Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; - vA += (m_mA * impulse) * m_JvAC; - wA += m_iA * impulse * m_JwA; - vB += (m_mB * impulse) * m_JvBD; - wB += m_iB * impulse * m_JwB; - vC -= (m_mC * impulse) * m_JvAC; - wC -= m_iC * impulse * m_JwC; - vD -= (m_mD * impulse) * m_JvBD; - wD -= m_iD * impulse * m_JwD; + vA += (m_mA * impulse) * m_JvAC; + wA += m_iA * impulse * m_JwA; + vB += (m_mB * impulse) * m_JvBD; + wB += m_iB * impulse * m_JwB; + vC -= (m_mC * impulse) * m_JvAC; + wC -= m_iC * impulse * m_JwC; + vD -= (m_mD * impulse) * m_JvBD; + wD -= m_iD * impulse * m_JwD; - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; + data.velocities[m_indexC].v = vC; + data.velocities[m_indexC].w = wC; + data.velocities[m_indexD].v = vD; + data.velocities[m_indexD].w = wD; } bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 cC = data.positions[m_indexC].c; + float32 aC = data.positions[m_indexC].a; + b2Vec2 cD = data.positions[m_indexD].c; + float32 aD = data.positions[m_indexD].a; - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); + b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - float32 linearError = 0.0f; + float32 linearError = 0.0f; - float32 coordinateA, coordinateB; + float32 coordinateA, coordinateB; - b2Vec2 JvAC, JvBD; - float32 JwA, JwB, JwC, JwD; - float32 mass = 0.0f; + b2Vec2 JvAC, JvBD; + float32 JwA, JwB, JwC, JwD; + float32 mass = 0.0f; - if (m_typeA == e_revoluteJoint) - { - JvAC.SetZero(); - JwA = 1.0f; - JwC = 1.0f; - mass += m_iA + m_iC; + if (m_typeA == e_revoluteJoint) + { + JvAC.SetZero(); + JwA = 1.0f; + JwC = 1.0f; + mass += m_iA + m_iC; - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - JvAC = u; - JwC = b2Cross(rC, u); - JwA = b2Cross(rA, u); - mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; + coordinateA = aA - aC - m_referenceAngleA; + } + else + { + b2Vec2 u = b2Mul(qC, m_localAxisC); + b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); + JvAC = u; + JwC = b2Cross(rC, u); + JwA = b2Cross(rA, u); + mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; - b2Vec2 pC = m_localAnchorC - m_lcC; - b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } + b2Vec2 pC = m_localAnchorC - m_lcC; + b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); + coordinateA = b2Dot(pA - pC, m_localAxisC); + } - if (m_typeB == e_revoluteJoint) - { - JvBD.SetZero(); - JwB = m_ratio; - JwD = m_ratio; - mass += m_ratio * m_ratio * (m_iB + m_iD); + if (m_typeB == e_revoluteJoint) + { + JvBD.SetZero(); + JwB = m_ratio; + JwD = m_ratio; + mass += m_ratio * m_ratio * (m_iB + m_iD); - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - JvBD = m_ratio * u; - JwD = m_ratio * b2Cross(rD, u); - JwB = m_ratio * b2Cross(rB, u); - mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; + coordinateB = aB - aD - m_referenceAngleB; + } + else + { + b2Vec2 u = b2Mul(qD, m_localAxisD); + b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); + JvBD = m_ratio * u; + JwD = m_ratio * b2Cross(rD, u); + JwB = m_ratio * b2Cross(rB, u); + mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; - b2Vec2 pD = m_localAnchorD - m_lcD; - b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } + b2Vec2 pD = m_localAnchorD - m_lcD; + b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); + coordinateB = b2Dot(pB - pD, m_localAxisD); + } - float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; + float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; - float32 impulse = 0.0f; - if (mass > 0.0f) - { - impulse = -C / mass; - } + float32 impulse = 0.0f; + if (mass > 0.0f) + { + impulse = -C / mass; + } - cA += m_mA * impulse * JvAC; - aA += m_iA * impulse * JwA; - cB += m_mB * impulse * JvBD; - aB += m_iB * impulse * JwB; - cC -= m_mC * impulse * JvAC; - aC -= m_iC * impulse * JwC; - cD -= m_mD * impulse * JvBD; - aD -= m_iD * impulse * JwD; + cA += m_mA * impulse * JvAC; + aA += m_iA * impulse * JwA; + cB += m_mB * impulse * JvBD; + aB += m_iB * impulse * JwB; + cC -= m_mC * impulse * JvAC; + aC -= m_iC * impulse * JwC; + cD -= m_mD * impulse * JvBD; + aD -= m_iD * impulse * JwD; - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - data.positions[m_indexC].c = cC; - data.positions[m_indexC].a = aC; - data.positions[m_indexD].c = cD; - data.positions[m_indexD].a = aD; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + data.positions[m_indexC].c = cC; + data.positions[m_indexC].a = aC; + data.positions[m_indexD].c = cD; + data.positions[m_indexD].a = aD; - // TODO_ERIN not implemented - return linearError < b2_linearSlop; + // TODO_ERIN not implemented + return linearError < b2_linearSlop; } b2Vec2 b2GearJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2GearJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 P = m_impulse * m_JvAC; - return inv_dt * P; + b2Vec2 P = m_impulse * m_JvAC; + return inv_dt * P; } float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const { - float32 L = m_impulse * m_JwA; - return inv_dt * L; + float32 L = m_impulse * m_JwA; + return inv_dt * L; } void b2GearJoint::SetRatio(float32 ratio) { - b2Assert(b2IsValid(ratio)); - m_ratio = ratio; + b2Assert(b2IsValid(ratio)); + m_ratio = ratio; } float32 b2GearJoint::GetRatio() const { - return m_ratio; + return m_ratio; } void b2GearJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - int32 index1 = m_joint1->m_index; - int32 index2 = m_joint2->m_index; + int32 index1 = m_joint1->m_index; + int32 index2 = m_joint2->m_index; - b2Log(" b2GearJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.joint1 = joints[%d];\n", index1); - b2Log(" jd.joint2 = joints[%d];\n", index2); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2GearJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.joint1 = joints[%d];\n", index1); + b2Log(" jd.joint2 = joints[%d];\n", index2); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2GearJoint.h b/external/Box2D/Dynamics/Joints/b2GearJoint.h index f926bf6ef1..fd3d7b2fa3 100644 --- a/external/Box2D/Dynamics/Joints/b2GearJoint.h +++ b/external/Box2D/Dynamics/Joints/b2GearJoint.h @@ -25,23 +25,23 @@ /// revolute or prismatic joints (any combination will work). struct b2GearJointDef : public b2JointDef { - b2GearJointDef() - { - type = e_gearJoint; - joint1 = NULL; - joint2 = NULL; - ratio = 1.0f; - } + b2GearJointDef() + { + type = e_gearJoint; + joint1 = NULL; + joint2 = NULL; + ratio = 1.0f; + } - /// The first revolute/prismatic joint attached to the gear joint. - b2Joint* joint1; + /// The first revolute/prismatic joint attached to the gear joint. + b2Joint* joint1; - /// The second revolute/prismatic joint attached to the gear joint. - b2Joint* joint2; + /// The second revolute/prismatic joint attached to the gear joint. + b2Joint* joint2; - /// The gear ratio. - /// @see b2GearJoint for explanation. - float32 ratio; + /// The gear ratio. + /// @see b2GearJoint for explanation. + float32 ratio; }; /// A gear joint is used to connect two joints together. Either joint @@ -56,70 +56,70 @@ struct b2GearJointDef : public b2JointDef class b2GearJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// Get the first joint. - b2Joint* GetJoint1() { return m_joint1; } + /// Get the first joint. + b2Joint* GetJoint1() { return m_joint1; } - /// Get the second joint. - b2Joint* GetJoint2() { return m_joint2; } + /// Get the second joint. + b2Joint* GetJoint2() { return m_joint2; } - /// Set/Get the gear ratio. - void SetRatio(float32 ratio); - float32 GetRatio() const; + /// Set/Get the gear ratio. + void SetRatio(float32 ratio); + float32 GetRatio() const; - /// Dump joint to dmLog - void Dump(); + /// Dump joint to dmLog + void Dump(); protected: - friend class b2Joint; - b2GearJoint(const b2GearJointDef* data); + friend class b2Joint; + b2GearJoint(const b2GearJointDef* data); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Joint* m_joint1; - b2Joint* m_joint2; + b2Joint* m_joint1; + b2Joint* m_joint2; - b2JointType m_typeA; - b2JointType m_typeB; + b2JointType m_typeA; + b2JointType m_typeB; - // Body A is connected to body C - // Body B is connected to body D - b2Body* m_bodyC; - b2Body* m_bodyD; + // Body A is connected to body C + // Body B is connected to body D + b2Body* m_bodyC; + b2Body* m_bodyD; - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localAnchorC; - b2Vec2 m_localAnchorD; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localAnchorC; + b2Vec2 m_localAnchorD; - b2Vec2 m_localAxisC; - b2Vec2 m_localAxisD; + b2Vec2 m_localAxisC; + b2Vec2 m_localAxisD; - float32 m_referenceAngleA; - float32 m_referenceAngleB; + float32 m_referenceAngleA; + float32 m_referenceAngleB; - float32 m_constant; - float32 m_ratio; + float32 m_constant; + float32 m_ratio; - float32 m_impulse; + float32 m_impulse; - // Solver temp - int32 m_indexA, m_indexB, m_indexC, m_indexD; - b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; - float32 m_mA, m_mB, m_mC, m_mD; - float32 m_iA, m_iB, m_iC, m_iD; - b2Vec2 m_JvAC, m_JvBD; - float32 m_JwA, m_JwB, m_JwC, m_JwD; - float32 m_mass; + // Solver temp + int32 m_indexA, m_indexB, m_indexC, m_indexD; + b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; + float32 m_mA, m_mB, m_mC, m_mD; + float32 m_iA, m_iB, m_iC, m_iD; + b2Vec2 m_JvAC, m_JvBD; + float32 m_JwA, m_JwB, m_JwC, m_JwD; + float32 m_mass; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2Joint.cpp b/external/Box2D/Dynamics/Joints/b2Joint.cpp index 6853b09f0b..dd55be94fa 100644 --- a/external/Box2D/Dynamics/Joints/b2Joint.cpp +++ b/external/Box2D/Dynamics/Joints/b2Joint.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -35,165 +36,176 @@ b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) { - b2Joint* joint = NULL; + b2Joint* joint = NULL; - switch (def->type) - { - case e_distanceJoint: - { - void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); - joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def); - } - break; + switch (def->type) + { + case e_distanceJoint: + { + void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); + joint = new (mem) b2DistanceJoint(static_cast(def)); + } + break; - case e_mouseJoint: - { - void* mem = allocator->Allocate(sizeof(b2MouseJoint)); - joint = new (mem) b2MouseJoint((b2MouseJointDef*)def); - } - break; + case e_mouseJoint: + { + void* mem = allocator->Allocate(sizeof(b2MouseJoint)); + joint = new (mem) b2MouseJoint(static_cast(def)); + } + break; - case e_prismaticJoint: - { - void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); - joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def); - } - break; + case e_prismaticJoint: + { + void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); + joint = new (mem) b2PrismaticJoint(static_cast(def)); + } + break; - case e_revoluteJoint: - { - void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); - joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def); - } - break; + case e_revoluteJoint: + { + void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); + joint = new (mem) b2RevoluteJoint(static_cast(def)); + } + break; - case e_pulleyJoint: - { - void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); - joint = new (mem) b2PulleyJoint((b2PulleyJointDef*)def); - } - break; + case e_pulleyJoint: + { + void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); + joint = new (mem) b2PulleyJoint(static_cast(def)); + } + break; - case e_gearJoint: - { - void* mem = allocator->Allocate(sizeof(b2GearJoint)); - joint = new (mem) b2GearJoint((b2GearJointDef*)def); - } - break; + case e_gearJoint: + { + void* mem = allocator->Allocate(sizeof(b2GearJoint)); + joint = new (mem) b2GearJoint(static_cast(def)); + } + break; - case e_wheelJoint: - { - void* mem = allocator->Allocate(sizeof(b2WheelJoint)); - joint = new (mem) b2WheelJoint((b2WheelJointDef*)def); - } - break; + case e_wheelJoint: + { + void* mem = allocator->Allocate(sizeof(b2WheelJoint)); + joint = new (mem) b2WheelJoint(static_cast(def)); + } + break; - case e_weldJoint: - { - void* mem = allocator->Allocate(sizeof(b2WeldJoint)); - joint = new (mem) b2WeldJoint((b2WeldJointDef*)def); - } - break; + case e_weldJoint: + { + void* mem = allocator->Allocate(sizeof(b2WeldJoint)); + joint = new (mem) b2WeldJoint(static_cast(def)); + } + break; - case e_frictionJoint: - { - void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); - joint = new (mem) b2FrictionJoint((b2FrictionJointDef*)def); - } - break; + case e_frictionJoint: + { + void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); + joint = new (mem) b2FrictionJoint(static_cast(def)); + } + break; - case e_ropeJoint: - { - void* mem = allocator->Allocate(sizeof(b2RopeJoint)); - joint = new (mem) b2RopeJoint((b2RopeJointDef*)def); - } - break; + case e_ropeJoint: + { + void* mem = allocator->Allocate(sizeof(b2RopeJoint)); + joint = new (mem) b2RopeJoint(static_cast(def)); + } + break; - default: - b2Assert(false); - break; - } + case e_motorJoint: + { + void* mem = allocator->Allocate(sizeof(b2MotorJoint)); + joint = new (mem) b2MotorJoint(static_cast(def)); + } + break; - return joint; + default: + b2Assert(false); + break; + } + + return joint; } void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) { - joint->~b2Joint(); - switch (joint->m_type) - { - case e_distanceJoint: - allocator->Free(joint, sizeof(b2DistanceJoint)); - break; + joint->~b2Joint(); + switch (joint->m_type) + { + case e_distanceJoint: + allocator->Free(joint, sizeof(b2DistanceJoint)); + break; - case e_mouseJoint: - allocator->Free(joint, sizeof(b2MouseJoint)); - break; + case e_mouseJoint: + allocator->Free(joint, sizeof(b2MouseJoint)); + break; - case e_prismaticJoint: - allocator->Free(joint, sizeof(b2PrismaticJoint)); - break; + case e_prismaticJoint: + allocator->Free(joint, sizeof(b2PrismaticJoint)); + break; - case e_revoluteJoint: - allocator->Free(joint, sizeof(b2RevoluteJoint)); - break; + case e_revoluteJoint: + allocator->Free(joint, sizeof(b2RevoluteJoint)); + break; - case e_pulleyJoint: - allocator->Free(joint, sizeof(b2PulleyJoint)); - break; + case e_pulleyJoint: + allocator->Free(joint, sizeof(b2PulleyJoint)); + break; - case e_gearJoint: - allocator->Free(joint, sizeof(b2GearJoint)); - break; + case e_gearJoint: + allocator->Free(joint, sizeof(b2GearJoint)); + break; - case e_wheelJoint: - allocator->Free(joint, sizeof(b2WheelJoint)); - break; + case e_wheelJoint: + allocator->Free(joint, sizeof(b2WheelJoint)); + break; - case e_weldJoint: - allocator->Free(joint, sizeof(b2WeldJoint)); - break; + case e_weldJoint: + allocator->Free(joint, sizeof(b2WeldJoint)); + break; - case e_frictionJoint: - allocator->Free(joint, sizeof(b2FrictionJoint)); - break; + case e_frictionJoint: + allocator->Free(joint, sizeof(b2FrictionJoint)); + break; - case e_ropeJoint: - allocator->Free(joint, sizeof(b2RopeJoint)); - break; + case e_ropeJoint: + allocator->Free(joint, sizeof(b2RopeJoint)); + break; - default: - b2Assert(false); - break; - } + case e_motorJoint: + allocator->Free(joint, sizeof(b2MotorJoint)); + break; + + default: + b2Assert(false); + break; + } } b2Joint::b2Joint(const b2JointDef* def) { - b2Assert(def->bodyA != def->bodyB); + b2Assert(def->bodyA != def->bodyB); - m_type = def->type; - m_prev = NULL; - m_next = NULL; - m_bodyA = def->bodyA; - m_bodyB = def->bodyB; - m_index = 0; - m_collideConnected = def->collideConnected; - m_islandFlag = false; - m_userData = def->userData; + m_type = def->type; + m_prev = NULL; + m_next = NULL; + m_bodyA = def->bodyA; + m_bodyB = def->bodyB; + m_index = 0; + m_collideConnected = def->collideConnected; + m_islandFlag = false; + m_userData = def->userData; - m_edgeA.joint = NULL; - m_edgeA.other = NULL; - m_edgeA.prev = NULL; - m_edgeA.next = NULL; + m_edgeA.joint = NULL; + m_edgeA.other = NULL; + m_edgeA.prev = NULL; + m_edgeA.next = NULL; - m_edgeB.joint = NULL; - m_edgeB.other = NULL; - m_edgeB.prev = NULL; - m_edgeB.next = NULL; + m_edgeB.joint = NULL; + m_edgeB.other = NULL; + m_edgeB.prev = NULL; + m_edgeB.next = NULL; } bool b2Joint::IsActive() const { - return m_bodyA->IsActive() && m_bodyB->IsActive(); + return m_bodyA->IsActive() && m_bodyB->IsActive(); } diff --git a/external/Box2D/Dynamics/Joints/b2Joint.h b/external/Box2D/Dynamics/Joints/b2Joint.h index b4ea576665..dd076b6b21 100644 --- a/external/Box2D/Dynamics/Joints/b2Joint.h +++ b/external/Box2D/Dynamics/Joints/b2Joint.h @@ -28,32 +28,33 @@ class b2BlockAllocator; enum b2JointType { - e_unknownJoint, - e_revoluteJoint, - e_prismaticJoint, - e_distanceJoint, - e_pulleyJoint, - e_mouseJoint, - e_gearJoint, - e_wheelJoint, + e_unknownJoint, + e_revoluteJoint, + e_prismaticJoint, + e_distanceJoint, + e_pulleyJoint, + e_mouseJoint, + e_gearJoint, + e_wheelJoint, e_weldJoint, - e_frictionJoint, - e_ropeJoint + e_frictionJoint, + e_ropeJoint, + e_motorJoint }; enum b2LimitState { - e_inactiveLimit, - e_atLowerLimit, - e_atUpperLimit, - e_equalLimits + e_inactiveLimit, + e_atLowerLimit, + e_atUpperLimit, + e_equalLimits }; struct b2Jacobian { - b2Vec2 linear; - float32 angularA; - float32 angularB; + b2Vec2 linear; + float32 angularA; + float32 angularB; }; /// A joint edge is used to connect bodies and joints together @@ -63,38 +64,38 @@ struct b2Jacobian /// nodes, one for each attached body. struct b2JointEdge { - b2Body* other; ///< provides quick access to the other body attached. - b2Joint* joint; ///< the joint - b2JointEdge* prev; ///< the previous joint edge in the body's joint list - b2JointEdge* next; ///< the next joint edge in the body's joint list + b2Body* other; ///< provides quick access to the other body attached. + b2Joint* joint; ///< the joint + b2JointEdge* prev; ///< the previous joint edge in the body's joint list + b2JointEdge* next; ///< the next joint edge in the body's joint list }; /// Joint definitions are used to construct joints. struct b2JointDef { - b2JointDef() - { - type = e_unknownJoint; - userData = NULL; - bodyA = NULL; - bodyB = NULL; - collideConnected = false; - } + b2JointDef() + { + type = e_unknownJoint; + userData = NULL; + bodyA = NULL; + bodyB = NULL; + collideConnected = false; + } - /// The joint type is set automatically for concrete joint types. - b2JointType type; + /// The joint type is set automatically for concrete joint types. + b2JointType type; - /// Use this to attach application specific data to your joints. - void* userData; + /// Use this to attach application specific data to your joints. + void* userData; - /// The first attached body. - b2Body* bodyA; + /// The first attached body. + b2Body* bodyA; - /// The second attached body. - b2Body* bodyB; + /// The second attached body. + b2Body* bodyB; - /// Set this flag to true if the attached bodies should collide. - bool collideConnected; + /// Set this flag to true if the attached bodies should collide. + bool collideConnected; }; /// The base joint class. Joints are used to constraint two bodies together in @@ -103,120 +104,123 @@ class b2Joint { public: - /// Get the type of the concrete joint. - b2JointType GetType() const; + /// Get the type of the concrete joint. + b2JointType GetType() const; - /// Get the first body attached to this joint. - b2Body* GetBodyA(); + /// Get the first body attached to this joint. + b2Body* GetBodyA(); - /// Get the second body attached to this joint. - b2Body* GetBodyB(); + /// Get the second body attached to this joint. + b2Body* GetBodyB(); - /// Get the anchor point on bodyA in world coordinates. - virtual b2Vec2 GetAnchorA() const = 0; + /// Get the anchor point on bodyA in world coordinates. + virtual b2Vec2 GetAnchorA() const = 0; - /// Get the anchor point on bodyB in world coordinates. - virtual b2Vec2 GetAnchorB() const = 0; + /// Get the anchor point on bodyB in world coordinates. + virtual b2Vec2 GetAnchorB() const = 0; - /// Get the reaction force on bodyB at the joint anchor in Newtons. - virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; + /// Get the reaction force on bodyB at the joint anchor in Newtons. + virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - /// Get the reaction torque on bodyB in N*m. - virtual float32 GetReactionTorque(float32 inv_dt) const = 0; + /// Get the reaction torque on bodyB in N*m. + virtual float32 GetReactionTorque(float32 inv_dt) const = 0; - /// Get the next joint the world joint list. - b2Joint* GetNext(); - const b2Joint* GetNext() const; + /// Get the next joint the world joint list. + b2Joint* GetNext(); + const b2Joint* GetNext() const; - /// Get the user data pointer. - void* GetUserData() const; + /// Get the user data pointer. + void* GetUserData() const; - /// Set the user data pointer. - void SetUserData(void* data); + /// Set the user data pointer. + void SetUserData(void* data); - /// Short-cut function to determine if either body is inactive. - bool IsActive() const; + /// Short-cut function to determine if either body is inactive. + bool IsActive() const; - /// Get collide connected. - /// Note: modifying the collide connect flag won't work correctly because - /// the flag is only checked when fixture AABBs begin to overlap. - bool GetCollideConnected() const; + /// Get collide connected. + /// Note: modifying the collide connect flag won't work correctly because + /// the flag is only checked when fixture AABBs begin to overlap. + bool GetCollideConnected() const; - /// Dump this joint to the log file. - virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } + /// Dump this joint to the log file. + virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } + + /// Shift the origin for any points stored in world coordinates. + virtual void ShiftOrigin(const b2Vec2& newOrigin) { B2_NOT_USED(newOrigin); } protected: - friend class b2World; - friend class b2Body; - friend class b2Island; - friend class b2GearJoint; + friend class b2World; + friend class b2Body; + friend class b2Island; + friend class b2GearJoint; - static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); - static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); + static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); + static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); - b2Joint(const b2JointDef* def); - virtual ~b2Joint() {} + b2Joint(const b2JointDef* def); + virtual ~b2Joint() {} - virtual void InitVelocityConstraints(const b2SolverData& data) = 0; - virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; + virtual void InitVelocityConstraints(const b2SolverData& data) = 0; + virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; - // This returns true if the position errors are within tolerance. - virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; + // This returns true if the position errors are within tolerance. + virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; - b2JointType m_type; - b2Joint* m_prev; - b2Joint* m_next; - b2JointEdge m_edgeA; - b2JointEdge m_edgeB; - b2Body* m_bodyA; - b2Body* m_bodyB; + b2JointType m_type; + b2Joint* m_prev; + b2Joint* m_next; + b2JointEdge m_edgeA; + b2JointEdge m_edgeB; + b2Body* m_bodyA; + b2Body* m_bodyB; - int32 m_index; + int32 m_index; - bool m_islandFlag; - bool m_collideConnected; + bool m_islandFlag; + bool m_collideConnected; - void* m_userData; + void* m_userData; }; inline b2JointType b2Joint::GetType() const { - return m_type; + return m_type; } inline b2Body* b2Joint::GetBodyA() { - return m_bodyA; + return m_bodyA; } inline b2Body* b2Joint::GetBodyB() { - return m_bodyB; + return m_bodyB; } inline b2Joint* b2Joint::GetNext() { - return m_next; + return m_next; } inline const b2Joint* b2Joint::GetNext() const { - return m_next; + return m_next; } inline void* b2Joint::GetUserData() const { - return m_userData; + return m_userData; } inline void b2Joint::SetUserData(void* data) { - m_userData = data; + m_userData = data; } inline bool b2Joint::GetCollideConnected() const { - return m_collideConnected; + return m_collideConnected; } #endif diff --git a/external/Box2D/Dynamics/Joints/b2MotorJoint.cpp b/external/Box2D/Dynamics/Joints/b2MotorJoint.cpp new file mode 100644 index 0000000000..e5bbcb165e --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2MotorJoint.cpp @@ -0,0 +1,304 @@ +/* +* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#include +#include +#include + +// Point-to-point constraint +// Cdot = v2 - v1 +// = v2 + cross(w2, r2) - v1 - cross(w1, r1) +// J = [-I -r1_skew I r2_skew ] +// Identity used: +// w k % (rx i + ry j) = w * (-ry i + rx j) + +// Angle constraint +// Cdot = w2 - w1 +// J = [0 0 -1 0 0 1] +// K = invI1 + invI2 + +void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB) +{ + bodyA = bA; + bodyB = bB; + b2Vec2 xB = bodyB->GetPosition(); + linearOffset = bodyA->GetLocalPoint(xB); + + float32 angleA = bodyA->GetAngle(); + float32 angleB = bodyB->GetAngle(); + angularOffset = angleB - angleA; +} + +b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def) +: b2Joint(def) +{ + m_linearOffset = def->linearOffset; + m_angularOffset = def->angularOffset; + + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + + m_maxForce = def->maxForce; + m_maxTorque = def->maxTorque; + m_correctionFactor = def->correctionFactor; +} + +void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data) +{ + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; + + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + b2Rot qA(aA), qB(aB); + + // Compute the effective mass matrix. + m_rA = b2Mul(qA, -m_localCenterA); + m_rB = b2Mul(qB, -m_localCenterB); + + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] + + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + b2Mat22 K; + K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; + K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; + + m_linearMass = K.GetInverse(); + + m_angularMass = iA + iB; + if (m_angularMass > 0.0f) + { + m_angularMass = 1.0f / m_angularMass; + } + + m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset); + m_angularError = aB - aA - m_angularOffset; + + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_linearImpulse *= data.step.dtRatio; + m_angularImpulse *= data.step.dtRatio; + + b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); + } + else + { + m_linearImpulse.SetZero(); + m_angularImpulse = 0.0f; + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data) +{ + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; + + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; + + float32 h = data.step.dt; + float32 inv_h = data.step.inv_dt; + + // Solve angular friction + { + float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError; + float32 impulse = -m_angularMass * Cdot; + + float32 oldImpulse = m_angularImpulse; + float32 maxImpulse = h * m_maxTorque; + m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_angularImpulse - oldImpulse; + + wA -= iA * impulse; + wB += iB * impulse; + } + + // Solve linear friction + { + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError; + + b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); + b2Vec2 oldImpulse = m_linearImpulse; + m_linearImpulse += impulse; + + float32 maxImpulse = h * m_maxForce; + + if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_linearImpulse.Normalize(); + m_linearImpulse *= maxImpulse; + } + + impulse = m_linearImpulse - oldImpulse; + + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); + + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } + + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; +} + +bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data) +{ + B2_NOT_USED(data); + + return true; +} + +b2Vec2 b2MotorJoint::GetAnchorA() const +{ + return m_bodyA->GetPosition(); +} + +b2Vec2 b2MotorJoint::GetAnchorB() const +{ + return m_bodyB->GetPosition(); +} + +b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const +{ + return inv_dt * m_linearImpulse; +} + +float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const +{ + return inv_dt * m_angularImpulse; +} + +void b2MotorJoint::SetMaxForce(float32 force) +{ + b2Assert(b2IsValid(force) && force >= 0.0f); + m_maxForce = force; +} + +float32 b2MotorJoint::GetMaxForce() const +{ + return m_maxForce; +} + +void b2MotorJoint::SetMaxTorque(float32 torque) +{ + b2Assert(b2IsValid(torque) && torque >= 0.0f); + m_maxTorque = torque; +} + +float32 b2MotorJoint::GetMaxTorque() const +{ + return m_maxTorque; +} + +void b2MotorJoint::SetCorrectionFactor(float32 factor) +{ + b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f); + m_correctionFactor = factor; +} + +float32 b2MotorJoint::GetCorrectionFactor() const +{ + return m_correctionFactor; +} + +void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset) +{ + if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_linearOffset = linearOffset; + } +} + +const b2Vec2& b2MotorJoint::GetLinearOffset() const +{ + return m_linearOffset; +} + +void b2MotorJoint::SetAngularOffset(float32 angularOffset) +{ + if (angularOffset != m_angularOffset) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_angularOffset = angularOffset; + } +} + +float32 b2MotorJoint::GetAngularOffset() const +{ + return m_angularOffset; +} + +void b2MotorJoint::Dump() +{ + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; + + b2Log(" b2MotorJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y); + b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset); + b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); + b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); + b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} diff --git a/external/Box2D/Dynamics/Joints/b2MotorJoint.h b/external/Box2D/Dynamics/Joints/b2MotorJoint.h new file mode 100644 index 0000000000..0b76d6fe7e --- /dev/null +++ b/external/Box2D/Dynamics/Joints/b2MotorJoint.h @@ -0,0 +1,133 @@ +/* +* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef B2_MOTOR_JOINT_H +#define B2_MOTOR_JOINT_H + +#include + +/// Motor joint definition. +struct b2MotorJointDef : public b2JointDef +{ + b2MotorJointDef() + { + type = e_motorJoint; + linearOffset.SetZero(); + angularOffset = 0.0f; + maxForce = 1.0f; + maxTorque = 1.0f; + correctionFactor = 0.3f; + } + + /// Initialize the bodies and offsets using the current transforms. + void Initialize(b2Body* bodyA, b2Body* bodyB); + + /// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters. + b2Vec2 linearOffset; + + /// The bodyB angle minus bodyA angle in radians. + float32 angularOffset; + + /// The maximum motor force in N. + float32 maxForce; + + /// The maximum motor torque in N-m. + float32 maxTorque; + + /// Position correction factor in the range [0,1]. + float32 correctionFactor; +}; + +/// A motor joint is used to control the relative motion +/// between two bodies. A typical usage is to control the movement +/// of a dynamic body with respect to the ground. +class b2MotorJoint : public b2Joint +{ +public: + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; + + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; + + /// Set/get the target linear offset, in frame A, in meters. + void SetLinearOffset(const b2Vec2& linearOffset); + const b2Vec2& GetLinearOffset() const; + + /// Set/get the target angular offset, in radians. + void SetAngularOffset(float32 angularOffset); + float32 GetAngularOffset() const; + + /// Set the maximum friction force in N. + void SetMaxForce(float32 force); + + /// Get the maximum friction force in N. + float32 GetMaxForce() const; + + /// Set the maximum friction torque in N*m. + void SetMaxTorque(float32 torque); + + /// Get the maximum friction torque in N*m. + float32 GetMaxTorque() const; + + /// Set the position correction factor in the range [0,1]. + void SetCorrectionFactor(float32 factor); + + /// Get the position correction factor in the range [0,1]. + float32 GetCorrectionFactor() const; + + /// Dump to b2Log + void Dump(); + +protected: + + friend class b2Joint; + + b2MotorJoint(const b2MotorJointDef* def); + + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); + + // Solver shared + b2Vec2 m_linearOffset; + float32 m_angularOffset; + b2Vec2 m_linearImpulse; + float32 m_angularImpulse; + float32 m_maxForce; + float32 m_maxTorque; + float32 m_correctionFactor; + + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + b2Vec2 m_linearError; + float32 m_angularError; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat22 m_linearMass; + float32 m_angularMass; +}; + +#endif diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp index 237d9d519a..ea96edde9b 100644 --- a/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2MouseJoint.cpp @@ -31,187 +31,192 @@ b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) : b2Joint(def) { - b2Assert(def->target.IsValid()); - b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); - b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); - b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); + b2Assert(def->target.IsValid()); + b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); + b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); + b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); - m_targetA = def->target; - m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); + m_targetA = def->target; + m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); - m_maxForce = def->maxForce; - m_impulse.SetZero(); + m_maxForce = def->maxForce; + m_impulse.SetZero(); - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; - m_beta = 0.0f; - m_gamma = 0.0f; + m_beta = 0.0f; + m_gamma = 0.0f; } void b2MouseJoint::SetTarget(const b2Vec2& target) { - if (m_bodyB->IsAwake() == false) - { - m_bodyB->SetAwake(true); - } - m_targetA = target; + if (m_bodyB->IsAwake() == false) + { + m_bodyB->SetAwake(true); + } + m_targetA = target; } const b2Vec2& b2MouseJoint::GetTarget() const { - return m_targetA; + return m_targetA; } void b2MouseJoint::SetMaxForce(float32 force) { - m_maxForce = force; + m_maxForce = force; } float32 b2MouseJoint::GetMaxForce() const { - return m_maxForce; + return m_maxForce; } void b2MouseJoint::SetFrequency(float32 hz) { - m_frequencyHz = hz; + m_frequencyHz = hz; } float32 b2MouseJoint::GetFrequency() const { - return m_frequencyHz; + return m_frequencyHz; } void b2MouseJoint::SetDampingRatio(float32 ratio) { - m_dampingRatio = ratio; + m_dampingRatio = ratio; } float32 b2MouseJoint::GetDampingRatio() const { - return m_dampingRatio; + return m_dampingRatio; } void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexB = m_bodyB->m_islandIndex; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassB = m_bodyB->m_invMass; - m_invIB = m_bodyB->m_invI; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassB = m_bodyB->m_invMass; + m_invIB = m_bodyB->m_invI; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qB(aB); + b2Rot qB(aB); - float32 mass = m_bodyB->GetMass(); + float32 mass = m_bodyB->GetMass(); - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; - // Damping coefficient - float32 d = 2.0f * mass * m_dampingRatio * omega; + // Damping coefficient + float32 d = 2.0f * mass * m_dampingRatio * omega; - // Spring stiffness - float32 k = mass * (omega * omega); + // Spring stiffness + float32 k = mass * (omega * omega); - // magic formulas - // gamma has units of inverse mass. - // beta has units of inverse time. - float32 h = data.step.dt; - b2Assert(d + h * k > b2_epsilon); - m_gamma = h * (d + h * k); - if (m_gamma != 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - m_beta = h * k * m_gamma; + // magic formulas + // gamma has units of inverse mass. + // beta has units of inverse time. + float32 h = data.step.dt; + b2Assert(d + h * k > b2_epsilon); + m_gamma = h * (d + h * k); + if (m_gamma != 0.0f) + { + m_gamma = 1.0f / m_gamma; + } + m_beta = h * k * m_gamma; - // Compute the effective mass matrix. - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + // Compute the effective mass matrix. + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - b2Mat22 K; - K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; - K.ex.y = -m_invIB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; + // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] + // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] + // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] + b2Mat22 K; + K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; + K.ex.y = -m_invIB * m_rB.x * m_rB.y; + K.ey.x = K.ex.y; + K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; - m_mass = K.GetInverse(); + m_mass = K.GetInverse(); - m_C = cB + m_rB - m_targetA; - m_C *= m_beta; + m_C = cB + m_rB - m_targetA; + m_C *= m_beta; - // Cheat with some damping - wB *= 0.98f; + // Cheat with some damping + wB *= 0.98f; - if (data.step.warmStarting) - { - m_impulse *= data.step.dtRatio; - vB += m_invMassB * m_impulse; - wB += m_invIB * b2Cross(m_rB, m_impulse); - } - else - { - m_impulse.SetZero(); - } + if (data.step.warmStarting) + { + m_impulse *= data.step.dtRatio; + vB += m_invMassB * m_impulse; + wB += m_invIB * b2Cross(m_rB, m_impulse); + } + else + { + m_impulse.SetZero(); + } - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - // Cdot = v + cross(w, r) - b2Vec2 Cdot = vB + b2Cross(wB, m_rB); - b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); + // Cdot = v + cross(w, r) + b2Vec2 Cdot = vB + b2Cross(wB, m_rB); + b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); - b2Vec2 oldImpulse = m_impulse; - m_impulse += impulse; - float32 maxImpulse = data.step.dt * m_maxForce; - if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_impulse *= maxImpulse / m_impulse.Length(); - } - impulse = m_impulse - oldImpulse; + b2Vec2 oldImpulse = m_impulse; + m_impulse += impulse; + float32 maxImpulse = data.step.dt * m_maxForce; + if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) + { + m_impulse *= maxImpulse / m_impulse.Length(); + } + impulse = m_impulse - oldImpulse; - vB += m_invMassB * impulse; - wB += m_invIB * b2Cross(m_rB, impulse); + vB += m_invMassB * impulse; + wB += m_invIB * b2Cross(m_rB, impulse); - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) { - B2_NOT_USED(data); - return true; + B2_NOT_USED(data); + return true; } b2Vec2 b2MouseJoint::GetAnchorA() const { - return m_targetA; + return m_targetA; } b2Vec2 b2MouseJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const { - return inv_dt * m_impulse; + return inv_dt * m_impulse; } float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * 0.0f; + return inv_dt * 0.0f; +} + +void b2MouseJoint::ShiftOrigin(const b2Vec2& newOrigin) +{ + m_targetA -= newOrigin; } diff --git a/external/Box2D/Dynamics/Joints/b2MouseJoint.h b/external/Box2D/Dynamics/Joints/b2MouseJoint.h index 1bbc194f4c..8b50a0e149 100644 --- a/external/Box2D/Dynamics/Joints/b2MouseJoint.h +++ b/external/Box2D/Dynamics/Joints/b2MouseJoint.h @@ -25,29 +25,29 @@ /// tuning parameters, and the time step. struct b2MouseJointDef : public b2JointDef { - b2MouseJointDef() - { - type = e_mouseJoint; - target.Set(0.0f, 0.0f); - maxForce = 0.0f; - frequencyHz = 5.0f; - dampingRatio = 0.7f; - } + b2MouseJointDef() + { + type = e_mouseJoint; + target.Set(0.0f, 0.0f); + maxForce = 0.0f; + frequencyHz = 5.0f; + dampingRatio = 0.7f; + } - /// The initial world target point. This is assumed - /// to coincide with the body anchor initially. - b2Vec2 target; + /// The initial world target point. This is assumed + /// to coincide with the body anchor initially. + b2Vec2 target; - /// The maximum constraint force that can be exerted - /// to move the candidate body. Usually you will express - /// as some multiple of the weight (multiplier * mass * gravity). - float32 maxForce; + /// The maximum constraint force that can be exerted + /// to move the candidate body. Usually you will express + /// as some multiple of the weight (multiplier * mass * gravity). + float32 maxForce; - /// The response speed. - float32 frequencyHz; + /// The response speed. + float32 frequencyHz; - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; }; /// A mouse joint is used to make a point on a body track a @@ -61,66 +61,69 @@ class b2MouseJoint : public b2Joint { public: - /// Implements b2Joint. - b2Vec2 GetAnchorA() const; + /// Implements b2Joint. + b2Vec2 GetAnchorA() const; - /// Implements b2Joint. - b2Vec2 GetAnchorB() const; + /// Implements b2Joint. + b2Vec2 GetAnchorB() const; - /// Implements b2Joint. - b2Vec2 GetReactionForce(float32 inv_dt) const; + /// Implements b2Joint. + b2Vec2 GetReactionForce(float32 inv_dt) const; - /// Implements b2Joint. - float32 GetReactionTorque(float32 inv_dt) const; + /// Implements b2Joint. + float32 GetReactionTorque(float32 inv_dt) const; - /// Use this to update the target point. - void SetTarget(const b2Vec2& target); - const b2Vec2& GetTarget() const; + /// Use this to update the target point. + void SetTarget(const b2Vec2& target); + const b2Vec2& GetTarget() const; - /// Set/get the maximum force in Newtons. - void SetMaxForce(float32 force); - float32 GetMaxForce() const; + /// Set/get the maximum force in Newtons. + void SetMaxForce(float32 force); + float32 GetMaxForce() const; - /// Set/get the frequency in Hertz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; + /// Set/get the frequency in Hertz. + void SetFrequency(float32 hz); + float32 GetFrequency() const; - /// Set/get the damping ratio (dimensionless). - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; + /// Set/get the damping ratio (dimensionless). + void SetDampingRatio(float32 ratio); + float32 GetDampingRatio() const; - /// The mouse joint does not support dumping. - void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } + /// The mouse joint does not support dumping. + void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } + + /// Implement b2Joint::ShiftOrigin + void ShiftOrigin(const b2Vec2& newOrigin); protected: - friend class b2Joint; + friend class b2Joint; - b2MouseJoint(const b2MouseJointDef* def); + b2MouseJoint(const b2MouseJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_localAnchorB; - b2Vec2 m_targetA; - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_beta; - - // Solver shared - b2Vec2 m_impulse; - float32 m_maxForce; - float32 m_gamma; + b2Vec2 m_localAnchorB; + b2Vec2 m_targetA; + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_beta; + + // Solver shared + b2Vec2 m_impulse; + float32 m_maxForce; + float32 m_gamma; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rB; - b2Vec2 m_localCenterB; - float32 m_invMassB; - float32 m_invIB; - b2Mat22 m_mass; - b2Vec2 m_C; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rB; + b2Vec2 m_localCenterB; + float32 m_invMassB; + float32 m_invIB; + b2Mat22 m_mass; + b2Vec2 m_C; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp index 4849f729f5..26f5396816 100644 --- a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp @@ -89,549 +89,538 @@ void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) { - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localXAxisA.Normalize(); - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_referenceAngle = def->referenceAngle; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localXAxisA.Normalize(); + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + m_referenceAngle = def->referenceAngle; - m_impulse.SetZero(); - m_motorMass = 0.0; - m_motorImpulse = 0.0f; + m_impulse.SetZero(); + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = def->maxMotorForce; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; + m_lowerTranslation = def->lowerTranslation; + m_upperTranslation = def->upperTranslation; + m_maxMotorForce = def->maxMotorForce; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; - m_axis.SetZero(); - m_perp.SetZero(); + m_axis.SetZero(); + m_perp.SetZero(); } void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - // Compute motor Jacobian and effective mass. - { - m_axis = b2Mul(qA, m_localXAxisA); - m_a1 = b2Cross(d + rA, m_axis); - m_a2 = b2Cross(rB, m_axis); + // Compute motor Jacobian and effective mass. + { + m_axis = b2Mul(qA, m_localXAxisA); + m_a1 = b2Cross(d + rA, m_axis); + m_a2 = b2Cross(rB, m_axis); - m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } + m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } - // Prismatic constraint. - { - m_perp = b2Mul(qA, m_localYAxisA); + // Prismatic constraint. + { + m_perp = b2Mul(qA, m_localYAxisA); - m_s1 = b2Cross(d + rA, m_perp); - m_s2 = b2Cross(rB, m_perp); + m_s1 = b2Cross(d + rA, m_perp); + m_s2 = b2Cross(rB, m_perp); - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; - float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For bodies with fixed rotation. - k22 = 1.0f; - } - float32 k23 = iA * m_a1 + iB * m_a2; - float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; + float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; + float32 k12 = iA * m_s1 + iB * m_s2; + float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For bodies with fixed rotation. + k22 = 1.0f; + } + float32 k23 = iA * m_a1 + iB * m_a2; + float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - m_K.ex.Set(k11, k12, k13); - m_K.ey.Set(k12, k22, k23); - m_K.ez.Set(k13, k23, k33); - } + m_K.ex.Set(k11, k12, k13); + m_K.ey.Set(k12, k22, k23); + m_K.ez.Set(k13, k23, k33); + } - // Compute motor and limit terms. - if (m_enableLimit) - { - float32 jointTranslation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitState = e_atLowerLimit; - m_impulse.z = 0.0f; - } - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitState = e_atUpperLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } + // Compute motor and limit terms. + if (m_enableLimit) + { + float32 jointTranslation = b2Dot(m_axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + m_limitState = e_equalLimits; + } + else if (jointTranslation <= m_lowerTranslation) + { + if (m_limitState != e_atLowerLimit) + { + m_limitState = e_atLowerLimit; + m_impulse.z = 0.0f; + } + } + else if (jointTranslation >= m_upperTranslation) + { + if (m_limitState != e_atUpperLimit) + { + m_limitState = e_atUpperLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } - if (m_enableMotor == false) - { - m_motorImpulse = 0.0f; - } + if (m_enableMotor == false) + { + m_motorImpulse = 0.0f; + } - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; - b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; - float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; - float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; + b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; + float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; + float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } + vB += mB * P; + wB += iB * LB; + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - float32 impulse = m_motorMass * (m_motorSpeed - Cdot); - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorForce; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; + // Solve linear motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits) + { + float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + float32 impulse = m_motorMass * (m_motorSpeed - Cdot); + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorForce; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; - b2Vec2 P = impulse * m_axis; - float32 LA = impulse * m_a1; - float32 LB = impulse * m_a2; + b2Vec2 P = impulse * m_axis; + float32 LA = impulse * m_a1; + float32 LB = impulse * m_a2; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; - } + vB += mB * P; + wB += iB * LB; + } - b2Vec2 Cdot1; - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; + b2Vec2 Cdot1; + Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; + Cdot1.y = wB - wA; - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - // Solve prismatic and limit constraint in block form. - float32 Cdot2; - Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + if (m_enableLimit && m_limitState != e_inactiveLimit) + { + // Solve prismatic and limit constraint in block form. + float32 Cdot2; + Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - b2Vec3 f1 = m_impulse; - b2Vec3 df = m_K.Solve33(-Cdot); - m_impulse += df; + b2Vec3 f1 = m_impulse; + b2Vec3 df = m_K.Solve33(-Cdot); + m_impulse += df; - if (m_limitState == e_atLowerLimit) - { - m_impulse.z = b2Max(m_impulse.z, 0.0f); - } - else if (m_limitState == e_atUpperLimit) - { - m_impulse.z = b2Min(m_impulse.z, 0.0f); - } + if (m_limitState == e_atLowerLimit) + { + m_impulse.z = b2Max(m_impulse.z, 0.0f); + } + else if (m_limitState == e_atUpperLimit) + { + m_impulse.z = b2Min(m_impulse.z, 0.0f); + } - // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) - b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); - b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); - m_impulse.x = f2r.x; - m_impulse.y = f2r.y; + // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) + b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); + b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); + m_impulse.x = f2r.x; + m_impulse.y = f2r.y; - df = m_impulse - f1; + df = m_impulse - f1; - b2Vec2 P = df.x * m_perp + df.z * m_axis; - float32 LA = df.x * m_s1 + df.y + df.z * m_a1; - float32 LB = df.x * m_s2 + df.y + df.z * m_a2; + b2Vec2 P = df.x * m_perp + df.z * m_axis; + float32 LA = df.x * m_s1 + df.y + df.z * m_a1; + float32 LB = df.x * m_s2 + df.y + df.z * m_a2; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; - } - else - { - // Limit is inactive, just solve the prismatic constraint in block form. - b2Vec2 df = m_K.Solve22(-Cdot1); - m_impulse.x += df.x; - m_impulse.y += df.y; + vB += mB * P; + wB += iB * LB; + } + else + { + // Limit is inactive, just solve the prismatic constraint in block form. + b2Vec2 df = m_K.Solve22(-Cdot1); + m_impulse.x += df.x; + m_impulse.y += df.y; - b2Vec2 P = df.x * m_perp; - float32 LA = df.x * m_s1 + df.y; - float32 LB = df.x * m_s2 + df.y; + b2Vec2 P = df.x * m_perp; + float32 LA = df.x * m_s1 + df.y; + float32 LB = df.x * m_s2 + df.y; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; + vB += mB * P; + wB += iB * LB; + } - b2Vec2 Cdot10 = Cdot1; - - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f) - { - b2Vec2 test = b2Mul22(m_K, df); - Cdot1.x += 0.0f; - } - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - // Compute fresh Jacobians - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; + // Compute fresh Jacobians + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; - b2Vec2 axis = b2Mul(qA, m_localXAxisA); - float32 a1 = b2Cross(d + rA, axis); - float32 a2 = b2Cross(rB, axis); - b2Vec2 perp = b2Mul(qA, m_localYAxisA); + b2Vec2 axis = b2Mul(qA, m_localXAxisA); + float32 a1 = b2Cross(d + rA, axis); + float32 a2 = b2Cross(rB, axis); + b2Vec2 perp = b2Mul(qA, m_localYAxisA); - float32 s1 = b2Cross(d + rA, perp); - float32 s2 = b2Cross(rB, perp); + float32 s1 = b2Cross(d + rA, perp); + float32 s2 = b2Cross(rB, perp); - b2Vec3 impulse; - b2Vec2 C1; - C1.x = b2Dot(perp, d); - C1.y = aB - aA - m_referenceAngle; + b2Vec3 impulse; + b2Vec2 C1; + C1.x = b2Dot(perp, d); + C1.y = aB - aA - m_referenceAngle; - float32 linearError = b2Abs(C1.x); - float32 angularError = b2Abs(C1.y); + float32 linearError = b2Abs(C1.x); + float32 angularError = b2Abs(C1.y); - bool active = false; - float32 C2 = 0.0f; - if (m_enableLimit) - { - float32 translation = b2Dot(axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - // Prevent large angular corrections - C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Max(linearError, b2Abs(translation)); - active = true; - } - else if (translation <= m_lowerTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = b2Max(linearError, m_lowerTranslation - translation); - active = true; - } - else if (translation >= m_upperTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = b2Max(linearError, translation - m_upperTranslation); - active = true; - } - } + bool active = false; + float32 C2 = 0.0f; + if (m_enableLimit) + { + float32 translation = b2Dot(axis, d); + if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) + { + // Prevent large angular corrections + C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); + linearError = b2Max(linearError, b2Abs(translation)); + active = true; + } + else if (translation <= m_lowerTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); + linearError = b2Max(linearError, m_lowerTranslation - translation); + active = true; + } + else if (translation >= m_upperTranslation) + { + // Prevent large linear corrections and allow some slop. + C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); + linearError = b2Max(linearError, translation - m_upperTranslation); + active = true; + } + } - if (active) - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k13 = iA * s1 * a1 + iB * s2 * a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For fixed rotation - k22 = 1.0f; - } - float32 k23 = iA * a1 + iB * a2; - float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; + if (active) + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k13 = iA * s1 * a1 + iB * s2 * a2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + // For fixed rotation + k22 = 1.0f; + } + float32 k23 = iA * a1 + iB * a2; + float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - b2Mat33 K; - K.ex.Set(k11, k12, k13); - K.ey.Set(k12, k22, k23); - K.ez.Set(k13, k23, k33); + b2Mat33 K; + K.ex.Set(k11, k12, k13); + K.ey.Set(k12, k22, k23); + K.ez.Set(k13, k23, k33); - b2Vec3 C; - C.x = C1.x; - C.y = C1.y; - C.z = C2; + b2Vec3 C; + C.x = C1.x; + C.y = C1.y; + C.z = C2; - impulse = K.Solve33(-C); - } - else - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - k22 = 1.0f; - } + impulse = K.Solve33(-C); + } + else + { + float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; + float32 k12 = iA * s1 + iB * s2; + float32 k22 = iA + iB; + if (k22 == 0.0f) + { + k22 = 1.0f; + } - b2Mat22 K; - K.ex.Set(k11, k12); - K.ey.Set(k12, k22); + b2Mat22 K; + K.ex.Set(k11, k12); + K.ey.Set(k12, k22); - b2Vec2 impulse1 = K.Solve(-C1); - impulse.x = impulse1.x; - impulse.y = impulse1.y; - impulse.z = 0.0f; - } + b2Vec2 impulse1 = K.Solve(-C1); + impulse.x = impulse1.x; + impulse.y = impulse1.y; + impulse.z = 0.0f; + } - b2Vec2 P = impulse.x * perp + impulse.z * axis; - float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; - float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; + b2Vec2 P = impulse.x * perp + impulse.z * axis; + float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; + float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; - cA -= mA * P; - aA -= iA * LA; - cB += mB * P; - aB += iB * LB; + cA -= mA * P; + aA -= iA * LA; + cB += mB * P; + aB += iB * LB; - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; + return linearError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2PrismaticJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PrismaticJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const { - return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); + return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); } float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * m_impulse.y; + return inv_dt * m_impulse.y; } float32 b2PrismaticJoint::GetJointTranslation() const { - b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); + b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); - float32 translation = b2Dot(d, axis); - return translation; + float32 translation = b2Dot(d, axis); + return translation; } float32 b2PrismaticJoint::GetJointSpeed() const { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; - b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); - b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); - b2Vec2 p1 = bA->m_sweep.c + rA; - b2Vec2 p2 = bB->m_sweep.c + rB; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); + b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); + b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); + b2Vec2 p1 = bA->m_sweep.c + rA; + b2Vec2 p2 = bB->m_sweep.c + rB; + b2Vec2 d = p2 - p1; + b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - b2Vec2 vA = bA->m_linearVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - float32 wB = bB->m_angularVelocity; + b2Vec2 vA = bA->m_linearVelocity; + b2Vec2 vB = bB->m_linearVelocity; + float32 wA = bA->m_angularVelocity; + float32 wB = bB->m_angularVelocity; - float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); - return speed; + float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); + return speed; } bool b2PrismaticJoint::IsLimitEnabled() const { - return m_enableLimit; + return m_enableLimit; } void b2PrismaticJoint::EnableLimit(bool flag) { - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } } float32 b2PrismaticJoint::GetLowerLimit() const { - return m_lowerTranslation; + return m_lowerTranslation; } float32 b2PrismaticJoint::GetUpperLimit() const { - return m_upperTranslation; + return m_upperTranslation; } void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) { - b2Assert(lower <= upper); - if (lower != m_lowerTranslation || upper != m_upperTranslation) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; - m_impulse.z = 0.0f; - } + b2Assert(lower <= upper); + if (lower != m_lowerTranslation || upper != m_upperTranslation) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_lowerTranslation = lower; + m_upperTranslation = upper; + m_impulse.z = 0.0f; + } } bool b2PrismaticJoint::IsMotorEnabled() const { - return m_enableMotor; + return m_enableMotor; } void b2PrismaticJoint::EnableMotor(bool flag) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; } void b2PrismaticJoint::SetMotorSpeed(float32 speed) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; } void b2PrismaticJoint::SetMaxMotorForce(float32 force) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorForce = force; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorForce = force; } float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const { - return inv_dt * m_motorImpulse; + return inv_dt * m_motorImpulse; } void b2PrismaticJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2PrismaticJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); - b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2PrismaticJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); + b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h index aca2859b45..6ef5d3ec04 100644 --- a/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h +++ b/external/Box2D/Dynamics/Joints/b2PrismaticJoint.h @@ -29,54 +29,54 @@ /// anchors and a local axis helps when saving and loading a game. struct b2PrismaticJointDef : public b2JointDef { - b2PrismaticJointDef() - { - type = e_prismaticJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - referenceAngle = 0.0f; - enableLimit = false; - lowerTranslation = 0.0f; - upperTranslation = 0.0f; - enableMotor = false; - maxMotorForce = 0.0f; - motorSpeed = 0.0f; - } + b2PrismaticJointDef() + { + type = e_prismaticJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + referenceAngle = 0.0f; + enableLimit = false; + lowerTranslation = 0.0f; + upperTranslation = 0.0f; + enableMotor = false; + maxMotorForce = 0.0f; + motorSpeed = 0.0f; + } - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and unit world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and unit world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The local translation unit axis in bodyA. - b2Vec2 localAxisA; + /// The local translation unit axis in bodyA. + b2Vec2 localAxisA; - /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. - float32 referenceAngle; + /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. + float32 referenceAngle; - /// Enable/disable the joint limit. - bool enableLimit; + /// Enable/disable the joint limit. + bool enableLimit; - /// The lower translation limit, usually in meters. - float32 lowerTranslation; + /// The lower translation limit, usually in meters. + float32 lowerTranslation; - /// The upper translation limit, usually in meters. - float32 upperTranslation; + /// The upper translation limit, usually in meters. + float32 upperTranslation; - /// Enable/disable the joint motor. - bool enableMotor; + /// Enable/disable the joint motor. + bool enableMotor; - /// The maximum motor torque, usually in N-m. - float32 maxMotorForce; + /// The maximum motor torque, usually in N-m. + float32 maxMotorForce; - /// The desired motor speed in radians per second. - float32 motorSpeed; + /// The desired motor speed in radians per second. + float32 motorSpeed; }; /// A prismatic joint. This joint provides one degree of freedom: translation @@ -86,111 +86,111 @@ struct b2PrismaticJointDef : public b2JointDef class b2PrismaticJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; - /// Is the joint limit enabled? - bool IsLimitEnabled() const; + /// Is the joint limit enabled? + bool IsLimitEnabled() const; - /// Enable/disable the joint limit. - void EnableLimit(bool flag); + /// Enable/disable the joint limit. + void EnableLimit(bool flag); - /// Get the lower joint limit, usually in meters. - float32 GetLowerLimit() const; + /// Get the lower joint limit, usually in meters. + float32 GetLowerLimit() const; - /// Get the upper joint limit, usually in meters. - float32 GetUpperLimit() const; + /// Get the upper joint limit, usually in meters. + float32 GetUpperLimit() const; - /// Set the joint limits, usually in meters. - void SetLimits(float32 lower, float32 upper); + /// Set the joint limits, usually in meters. + void SetLimits(float32 lower, float32 upper); - /// Is the joint motor enabled? - bool IsMotorEnabled() const; + /// Is the joint motor enabled? + bool IsMotorEnabled() const; - /// Enable/disable the joint motor. - void EnableMotor(bool flag); + /// Enable/disable the joint motor. + void EnableMotor(bool flag); - /// Set the motor speed, usually in meters per second. - void SetMotorSpeed(float32 speed); + /// Set the motor speed, usually in meters per second. + void SetMotorSpeed(float32 speed); - /// Get the motor speed, usually in meters per second. - float32 GetMotorSpeed() const; + /// Get the motor speed, usually in meters per second. + float32 GetMotorSpeed() const; - /// Set the maximum motor force, usually in N. - void SetMaxMotorForce(float32 force); - float32 GetMaxMotorForce() const { return m_maxMotorForce; } + /// Set the maximum motor force, usually in N. + void SetMaxMotorForce(float32 force); + float32 GetMaxMotorForce() const { return m_maxMotorForce; } - /// Get the current motor force given the inverse time step, usually in N. - float32 GetMotorForce(float32 inv_dt) const; + /// Get the current motor force given the inverse time step, usually in N. + float32 GetMotorForce(float32 inv_dt) const; - /// Dump to b2Log - void Dump(); + /// Dump to b2Log + void Dump(); protected: - friend class b2Joint; - friend class b2GearJoint; - b2PrismaticJoint(const b2PrismaticJointDef* def); + friend class b2Joint; + friend class b2GearJoint; + b2PrismaticJoint(const b2PrismaticJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - float32 m_referenceAngle; - b2Vec3 m_impulse; - float32 m_motorImpulse; - float32 m_lowerTranslation; - float32 m_upperTranslation; - float32 m_maxMotorForce; - float32 m_motorSpeed; - bool m_enableLimit; - bool m_enableMotor; - b2LimitState m_limitState; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; + float32 m_referenceAngle; + b2Vec3 m_impulse; + float32 m_motorImpulse; + float32 m_lowerTranslation; + float32 m_upperTranslation; + float32 m_maxMotorForce; + float32 m_motorSpeed; + bool m_enableLimit; + bool m_enableMotor; + b2LimitState m_limitState; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - b2Mat33 m_K; - float32 m_motorMass; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Vec2 m_axis, m_perp; + float32 m_s1, m_s2; + float32 m_a1, m_a2; + b2Mat33 m_K; + float32 m_motorMass; }; inline float32 b2PrismaticJoint::GetMotorSpeed() const { - return m_motorSpeed; + return m_motorSpeed; } #endif diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp index da30fae222..9cd340f1b7 100644 --- a/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2PulleyJoint.cpp @@ -33,300 +33,316 @@ // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, - const b2Vec2& groundA, const b2Vec2& groundB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 r) + const b2Vec2& groundA, const b2Vec2& groundB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 r) { - bodyA = bA; - bodyB = bB; - groundAnchorA = groundA; - groundAnchorB = groundB; - localAnchorA = bodyA->GetLocalPoint(anchorA); - localAnchorB = bodyB->GetLocalPoint(anchorB); - b2Vec2 dA = anchorA - groundA; - lengthA = dA.Length(); - b2Vec2 dB = anchorB - groundB; - lengthB = dB.Length(); - ratio = r; - b2Assert(ratio > b2_epsilon); + bodyA = bA; + bodyB = bB; + groundAnchorA = groundA; + groundAnchorB = groundB; + localAnchorA = bodyA->GetLocalPoint(anchorA); + localAnchorB = bodyB->GetLocalPoint(anchorB); + b2Vec2 dA = anchorA - groundA; + lengthA = dA.Length(); + b2Vec2 dB = anchorB - groundB; + lengthB = dB.Length(); + ratio = r; + b2Assert(ratio > b2_epsilon); } b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) : b2Joint(def) { - m_groundAnchorA = def->groundAnchorA; - m_groundAnchorB = def->groundAnchorB; - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; + m_groundAnchorA = def->groundAnchorA; + m_groundAnchorB = def->groundAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; - m_lengthA = def->lengthA; - m_lengthB = def->lengthB; + m_lengthA = def->lengthA; + m_lengthB = def->lengthB; - b2Assert(def->ratio != 0.0f); - m_ratio = def->ratio; + b2Assert(def->ratio != 0.0f); + m_ratio = def->ratio; - m_constant = def->lengthA + m_ratio * def->lengthB; + m_constant = def->lengthA + m_ratio * def->lengthB; - m_impulse = 0.0f; + m_impulse = 0.0f; } void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // Get the pulley axes. - m_uA = cA + m_rA - m_groundAnchorA; - m_uB = cB + m_rB - m_groundAnchorB; + // Get the pulley axes. + m_uA = cA + m_rA - m_groundAnchorA; + m_uB = cB + m_rB - m_groundAnchorB; - float32 lengthA = m_uA.Length(); - float32 lengthB = m_uB.Length(); + float32 lengthA = m_uA.Length(); + float32 lengthB = m_uB.Length(); - if (lengthA > 10.0f * b2_linearSlop) - { - m_uA *= 1.0f / lengthA; - } - else - { - m_uA.SetZero(); - } + if (lengthA > 10.0f * b2_linearSlop) + { + m_uA *= 1.0f / lengthA; + } + else + { + m_uA.SetZero(); + } - if (lengthB > 10.0f * b2_linearSlop) - { - m_uB *= 1.0f / lengthB; - } - else - { - m_uB.SetZero(); - } + if (lengthB > 10.0f * b2_linearSlop) + { + m_uB *= 1.0f / lengthB; + } + else + { + m_uB.SetZero(); + } - // Compute effective mass. - float32 ruA = b2Cross(m_rA, m_uA); - float32 ruB = b2Cross(m_rB, m_uB); + // Compute effective mass. + float32 ruA = b2Cross(m_rA, m_uA); + float32 ruB = b2Cross(m_rB, m_uB); - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; - m_mass = mA + m_ratio * m_ratio * mB; + m_mass = mA + m_ratio * m_ratio * mB; - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } - if (data.step.warmStarting) - { - // Scale impulses to support variable time steps. - m_impulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale impulses to support variable time steps. + m_impulse *= data.step.dtRatio; - // Warm starting. - b2Vec2 PA = -(m_impulse) * m_uA; - b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; + // Warm starting. + b2Vec2 PA = -(m_impulse) * m_uA; + b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - } - else - { - m_impulse = 0.0f; - } + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); + } + else + { + m_impulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; + float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; - b2Vec2 PA = -impulse * m_uA; - b2Vec2 PB = -m_ratio * impulse * m_uB; - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); + b2Vec2 PA = -impulse * m_uA; + b2Vec2 PB = -m_ratio * impulse * m_uB; + vA += m_invMassA * PA; + wA += m_invIA * b2Cross(m_rA, PA); + vB += m_invMassB * PB; + wB += m_invIB * b2Cross(m_rB, PB); - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // Get the pulley axes. - b2Vec2 uA = cA + rA - m_groundAnchorA; - b2Vec2 uB = cB + rB - m_groundAnchorB; + // Get the pulley axes. + b2Vec2 uA = cA + rA - m_groundAnchorA; + b2Vec2 uB = cB + rB - m_groundAnchorB; - float32 lengthA = uA.Length(); - float32 lengthB = uB.Length(); + float32 lengthA = uA.Length(); + float32 lengthB = uB.Length(); - if (lengthA > 10.0f * b2_linearSlop) - { - uA *= 1.0f / lengthA; - } - else - { - uA.SetZero(); - } + if (lengthA > 10.0f * b2_linearSlop) + { + uA *= 1.0f / lengthA; + } + else + { + uA.SetZero(); + } - if (lengthB > 10.0f * b2_linearSlop) - { - uB *= 1.0f / lengthB; - } - else - { - uB.SetZero(); - } + if (lengthB > 10.0f * b2_linearSlop) + { + uB *= 1.0f / lengthB; + } + else + { + uB.SetZero(); + } - // Compute effective mass. - float32 ruA = b2Cross(rA, uA); - float32 ruB = b2Cross(rB, uB); + // Compute effective mass. + float32 ruA = b2Cross(rA, uA); + float32 ruB = b2Cross(rB, uB); - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; + float32 mA = m_invMassA + m_invIA * ruA * ruA; + float32 mB = m_invMassB + m_invIB * ruB * ruB; - float32 mass = mA + m_ratio * m_ratio * mB; + float32 mass = mA + m_ratio * m_ratio * mB; - if (mass > 0.0f) - { - mass = 1.0f / mass; - } + if (mass > 0.0f) + { + mass = 1.0f / mass; + } - float32 C = m_constant - lengthA - m_ratio * lengthB; - float32 linearError = b2Abs(C); + float32 C = m_constant - lengthA - m_ratio * lengthB; + float32 linearError = b2Abs(C); - float32 impulse = -mass * C; + float32 impulse = -mass * C; - b2Vec2 PA = -impulse * uA; - b2Vec2 PB = -m_ratio * impulse * uB; + b2Vec2 PA = -impulse * uA; + b2Vec2 PB = -m_ratio * impulse * uB; - cA += m_invMassA * PA; - aA += m_invIA * b2Cross(rA, PA); - cB += m_invMassB * PB; - aB += m_invIB * b2Cross(rB, PB); + cA += m_invMassA * PA; + aA += m_invIA * b2Cross(rA, PA); + cB += m_invMassB * PB; + aB += m_invIB * b2Cross(rB, PB); - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return linearError < b2_linearSlop; + return linearError < b2_linearSlop; } b2Vec2 b2PulleyJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PulleyJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 P = m_impulse * m_uB; - return inv_dt * P; + b2Vec2 P = m_impulse * m_uB; + return inv_dt * P; } float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const { - B2_NOT_USED(inv_dt); - return 0.0f; + B2_NOT_USED(inv_dt); + return 0.0f; } b2Vec2 b2PulleyJoint::GetGroundAnchorA() const { - return m_groundAnchorA; + return m_groundAnchorA; } b2Vec2 b2PulleyJoint::GetGroundAnchorB() const { - return m_groundAnchorB; + return m_groundAnchorB; } float32 b2PulleyJoint::GetLengthA() const { - b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 s = m_groundAnchorA; - b2Vec2 d = p - s; - return d.Length(); + return m_lengthA; } float32 b2PulleyJoint::GetLengthB() const { - b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 s = m_groundAnchorB; - b2Vec2 d = p - s; - return d.Length(); + return m_lengthB; } float32 b2PulleyJoint::GetRatio() const { - return m_ratio; + return m_ratio; +} + +float32 b2PulleyJoint::GetCurrentLengthA() const +{ + b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); + b2Vec2 s = m_groundAnchorA; + b2Vec2 d = p - s; + return d.Length(); +} + +float32 b2PulleyJoint::GetCurrentLengthB() const +{ + b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); + b2Vec2 s = m_groundAnchorB; + b2Vec2 d = p - s; + return d.Length(); } void b2PulleyJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2PulleyJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); - b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); - b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2PulleyJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); + b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); + b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); + b2Log(" jd.ratio = %.15lef;\n", m_ratio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); +} + +void b2PulleyJoint::ShiftOrigin(const b2Vec2& newOrigin) +{ + m_groundAnchorA -= newOrigin; + m_groundAnchorB -= newOrigin; } diff --git a/external/Box2D/Dynamics/Joints/b2PulleyJoint.h b/external/Box2D/Dynamics/Joints/b2PulleyJoint.h index 2f6df4395c..44843e7b41 100644 --- a/external/Box2D/Dynamics/Joints/b2PulleyJoint.h +++ b/external/Box2D/Dynamics/Joints/b2PulleyJoint.h @@ -27,45 +27,45 @@ const float32 b2_minPulleyLength = 2.0f; /// two dynamic body anchor points, and a pulley ratio. struct b2PulleyJointDef : public b2JointDef { - b2PulleyJointDef() - { - type = e_pulleyJoint; - groundAnchorA.Set(-1.0f, 1.0f); - groundAnchorB.Set(1.0f, 1.0f); - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - lengthA = 0.0f; - lengthB = 0.0f; - ratio = 1.0f; - collideConnected = true; - } + b2PulleyJointDef() + { + type = e_pulleyJoint; + groundAnchorA.Set(-1.0f, 1.0f); + groundAnchorB.Set(1.0f, 1.0f); + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + lengthA = 0.0f; + lengthB = 0.0f; + ratio = 1.0f; + collideConnected = true; + } - /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 ratio); + /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. + void Initialize(b2Body* bodyA, b2Body* bodyB, + const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, + const b2Vec2& anchorA, const b2Vec2& anchorB, + float32 ratio); - /// The first ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorA; + /// The first ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorA; - /// The second ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorB; + /// The second ground anchor in world coordinates. This point never moves. + b2Vec2 groundAnchorB; - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The a reference length for the segment attached to bodyA. - float32 lengthA; + /// The a reference length for the segment attached to bodyA. + float32 lengthA; - /// The a reference length for the segment attached to bodyB. - float32 lengthB; + /// The a reference length for the segment attached to bodyB. + float32 lengthB; - /// The pulley ratio, used to simulate a block-and-tackle. - float32 ratio; + /// The pulley ratio, used to simulate a block-and-tackle. + float32 ratio; }; /// The pulley joint is connected to two bodies and two fixed ground points. @@ -79,65 +79,74 @@ struct b2PulleyJointDef : public b2JointDef class b2PulleyJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// Get the first ground anchor. - b2Vec2 GetGroundAnchorA() const; + /// Get the first ground anchor. + b2Vec2 GetGroundAnchorA() const; - /// Get the second ground anchor. - b2Vec2 GetGroundAnchorB() const; + /// Get the second ground anchor. + b2Vec2 GetGroundAnchorB() const; - /// Get the current length of the segment attached to bodyA. - float32 GetLengthA() const; + /// Get the current length of the segment attached to bodyA. + float32 GetLengthA() const; - /// Get the current length of the segment attached to bodyB. - float32 GetLengthB() const; + /// Get the current length of the segment attached to bodyB. + float32 GetLengthB() const; - /// Get the pulley ratio. - float32 GetRatio() const; + /// Get the pulley ratio. + float32 GetRatio() const; - /// Dump joint to dmLog - void Dump(); + /// Get the current length of the segment attached to bodyA. + float32 GetCurrentLengthA() const; + + /// Get the current length of the segment attached to bodyB. + float32 GetCurrentLengthB() const; + + /// Dump joint to dmLog + void Dump(); + + /// Implement b2Joint::ShiftOrigin + void ShiftOrigin(const b2Vec2& newOrigin); protected: - friend class b2Joint; - b2PulleyJoint(const b2PulleyJointDef* data); + friend class b2Joint; + b2PulleyJoint(const b2PulleyJointDef* data); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - b2Vec2 m_groundAnchorA; - b2Vec2 m_groundAnchorB; - float32 m_lengthA; - float32 m_lengthB; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_constant; - float32 m_ratio; - float32 m_impulse; + b2Vec2 m_groundAnchorA; + b2Vec2 m_groundAnchorB; + float32 m_lengthA; + float32 m_lengthB; + + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_constant; + float32 m_ratio; + float32 m_impulse; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_uA; - b2Vec2 m_uB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_uA; + b2Vec2 m_uB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp index e265d8192b..64bd19070d 100644 --- a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp @@ -35,470 +35,468 @@ void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; - m_impulse.SetZero(); - m_motorImpulse = 0.0f; + m_impulse.SetZero(); + m_motorImpulse = 0.0f; - m_lowerAngle = def->lowerAngle; - m_upperAngle = def->upperAngle; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; + m_lowerAngle = def->lowerAngle; + m_upperAngle = def->upperAngle; + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableLimit = def->enableLimit; + m_enableMotor = def->enableMotor; + m_limitState = e_inactiveLimit; } void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - bool fixedRotation = (iA + iB == 0.0f); + bool fixedRotation = (iA + iB == 0.0f); - m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; + m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; + m_mass.ex.y = m_mass.ey.x; + m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; + m_mass.ex.z = m_mass.ez.x; + m_mass.ey.z = m_mass.ez.y; + m_mass.ez.z = iA + iB; - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } - if (m_enableMotor == false || fixedRotation) - { - m_motorImpulse = 0.0f; - } + if (m_enableMotor == false || fixedRotation) + { + m_motorImpulse = 0.0f; + } - if (m_enableLimit && fixedRotation == false) - { - float32 jointAngle = aB - aA - m_referenceAngle; - if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) - { - m_limitState = e_equalLimits; - } - else if (jointAngle <= m_lowerAngle) - { - if (m_limitState != e_atLowerLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointAngle >= m_upperAngle) - { - if (m_limitState != e_atUpperLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - } + if (m_enableLimit && fixedRotation == false) + { + float32 jointAngle = aB - aA - m_referenceAngle; + if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) + { + m_limitState = e_equalLimits; + } + else if (jointAngle <= m_lowerAngle) + { + if (m_limitState != e_atLowerLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atLowerLimit; + } + else if (jointAngle >= m_upperAngle) + { + if (m_limitState != e_atUpperLimit) + { + m_impulse.z = 0.0f; + } + m_limitState = e_atUpperLimit; + } + else + { + m_limitState = e_inactiveLimit; + m_impulse.z = 0.0f; + } + } + else + { + m_limitState = e_inactiveLimit; + } - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; - b2Vec2 P(m_impulse.x, m_impulse.y); + b2Vec2 P(m_impulse.x, m_impulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); + } + else + { + m_impulse.SetZero(); + m_motorImpulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - bool fixedRotation = (iA + iB == 0.0f); + bool fixedRotation = (iA + iB == 0.0f); - // Solve motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; + // Solve motor constraint. + if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; - wA -= iA * impulse; - wB += iB * impulse; - } + wA -= iA * impulse; + wB += iB * impulse; + } - // Solve limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + // Solve limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - b2Vec3 impulse = -m_mass.Solve33(Cdot); + b2Vec3 impulse = -m_mass.Solve33(Cdot); - if (m_limitState == e_equalLimits) - { - m_impulse += impulse; - } - else if (m_limitState == e_atLowerLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse < 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - else if (m_limitState == e_atUpperLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse > 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } + if (m_limitState == e_equalLimits) + { + m_impulse += impulse; + } + else if (m_limitState == e_atLowerLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse < 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } + else if (m_limitState == e_atUpperLimit) + { + float32 newImpulse = m_impulse.z + impulse.z; + if (newImpulse > 0.0f) + { + b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); + b2Vec2 reduced = m_mass.Solve22(rhs); + impulse.x = reduced.x; + impulse.y = reduced.y; + impulse.z = -m_impulse.z; + m_impulse.x += reduced.x; + m_impulse.y += reduced.y; + m_impulse.z = 0.0f; + } + else + { + m_impulse += impulse; + } + } - b2Vec2 P(impulse.x, impulse.y); + b2Vec2 P(impulse.x, impulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - else - { - // Solve point-to-point constraint - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse = m_mass.Solve22(-Cdot); + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } + else + { + // Solve point-to-point constraint + b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + b2Vec2 impulse = m_mass.Solve22(-Cdot); - m_impulse.x += impulse.x; - m_impulse.y += impulse.y; + m_impulse.x += impulse.x; + m_impulse.y += impulse.y; - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); + vA -= mA * impulse; + wA -= iA * b2Cross(m_rA, impulse); - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } + vB += mB * impulse; + wB += iB * b2Cross(m_rB, impulse); + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - float32 angularError = 0.0f; - float32 positionError = 0.0f; + float32 angularError = 0.0f; + float32 positionError = 0.0f; - bool fixedRotation = (m_invIA + m_invIB == 0.0f); + bool fixedRotation = (m_invIA + m_invIB == 0.0f); - // Solve angular limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - float32 angle = aB - aA - m_referenceAngle; - float32 limitImpulse = 0.0f; + // Solve angular limit constraint. + if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) + { + float32 angle = aB - aA - m_referenceAngle; + float32 limitImpulse = 0.0f; - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - angularError = b2Abs(C); - } - else if (m_limitState == e_atLowerLimit) - { - float32 C = angle - m_lowerAngle; - angularError = -C; + if (m_limitState == e_equalLimits) + { + // Prevent large angular corrections + float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + angularError = b2Abs(C); + } + else if (m_limitState == e_atLowerLimit) + { + float32 C = angle - m_lowerAngle; + angularError = -C; - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); - limitImpulse = -m_motorMass * C; - } - else if (m_limitState == e_atUpperLimit) - { - float32 C = angle - m_upperAngle; - angularError = C; + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); + limitImpulse = -m_motorMass * C; + } + else if (m_limitState == e_atUpperLimit) + { + float32 C = angle - m_upperAngle; + angularError = C; - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - } + // Prevent large angular corrections and allow some slop. + C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); + limitImpulse = -m_motorMass * C; + } - aA -= m_invIA * limitImpulse; - aB += m_invIB * limitImpulse; - } + aA -= m_invIA * limitImpulse; + aB += m_invIB * limitImpulse; + } - // Solve point-to-point constraint. - { - qA.Set(aA); - qB.Set(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + // Solve point-to-point constraint. + { + qA.Set(aA); + qB.Set(aB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 C = cB + rB - cA - rA; - positionError = C.Length(); + b2Vec2 C = cB + rB - cA - rA; + positionError = C.Length(); - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Mat22 K; - K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; - K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; + b2Mat22 K; + K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; + K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; + K.ey.x = K.ex.y; + K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; - b2Vec2 impulse = -K.Solve(C); + b2Vec2 impulse = -K.Solve(C); - cA -= mA * impulse; - aA -= iA * b2Cross(rA, impulse); + cA -= mA * impulse; + aA -= iA * b2Cross(rA, impulse); - cB += mB * impulse; - aB += iB * b2Cross(rB, impulse); - } + cB += mB * impulse; + aB += iB * b2Cross(rB, impulse); + } - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; + + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2RevoluteJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RevoluteJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; } float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * m_impulse.z; + return inv_dt * m_impulse.z; } float32 b2RevoluteJoint::GetJointAngle() const { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; } float32 b2RevoluteJoint::GetJointSpeed() const { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_angularVelocity - bA->m_angularVelocity; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; + return bB->m_angularVelocity - bA->m_angularVelocity; } bool b2RevoluteJoint::IsMotorEnabled() const { - return m_enableMotor; + return m_enableMotor; } void b2RevoluteJoint::EnableMotor(bool flag) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; } float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const { - return inv_dt * m_motorImpulse; + return inv_dt * m_motorImpulse; } void b2RevoluteJoint::SetMotorSpeed(float32 speed) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; } void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; } bool b2RevoluteJoint::IsLimitEnabled() const { - return m_enableLimit; + return m_enableLimit; } void b2RevoluteJoint::EnableLimit(bool flag) { - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } + if (flag != m_enableLimit) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableLimit = flag; + m_impulse.z = 0.0f; + } } float32 b2RevoluteJoint::GetLowerLimit() const { - return m_lowerAngle; + return m_lowerAngle; } float32 b2RevoluteJoint::GetUpperLimit() const { - return m_upperAngle; + return m_upperAngle; } void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) { - b2Assert(lower <= upper); - - if (lower != m_lowerAngle || upper != m_upperAngle) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_impulse.z = 0.0f; - m_lowerAngle = lower; - m_upperAngle = upper; - } + b2Assert(lower <= upper); + + if (lower != m_lowerAngle || upper != m_upperAngle) + { + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_impulse.z = 0.0f; + m_lowerAngle = lower; + m_upperAngle = upper; + } } void b2RevoluteJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2RevoluteJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); - b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2RevoluteJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); + b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); + b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h index 978f16259a..bbed4a6cb2 100644 --- a/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h +++ b/external/Box2D/Dynamics/Joints/b2RevoluteJoint.h @@ -34,51 +34,51 @@ /// the joints will be broken. struct b2RevoluteJointDef : public b2JointDef { - b2RevoluteJointDef() - { - type = e_revoluteJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - lowerAngle = 0.0f; - upperAngle = 0.0f; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - enableLimit = false; - enableMotor = false; - } + b2RevoluteJointDef() + { + type = e_revoluteJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + lowerAngle = 0.0f; + upperAngle = 0.0f; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + enableLimit = false; + enableMotor = false; + } - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; - /// A flag to enable joint limits. - bool enableLimit; + /// A flag to enable joint limits. + bool enableLimit; - /// The lower angle for the joint limit (radians). - float32 lowerAngle; + /// The lower angle for the joint limit (radians). + float32 lowerAngle; - /// The upper angle for the joint limit (radians). - float32 upperAngle; + /// The upper angle for the joint limit (radians). + float32 upperAngle; - /// A flag to enable the joint motor. - bool enableMotor; + /// A flag to enable the joint motor. + bool enableMotor; - /// The desired motor speed. Usually in radians per second. - float32 motorSpeed; + /// The desired motor speed. Usually in radians per second. + float32 motorSpeed; - /// The maximum motor torque used to achieve the desired motor speed. - /// Usually in N-m. - float32 maxMotorTorque; + /// The maximum motor torque used to achieve the desired motor speed. + /// Usually in N-m. + float32 maxMotorTorque; }; /// A revolute joint constrains two bodies to share a common point while they @@ -90,115 +90,115 @@ struct b2RevoluteJointDef : public b2JointDef class b2RevoluteJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } - /// Get the current joint angle in radians. - float32 GetJointAngle() const; + /// Get the current joint angle in radians. + float32 GetJointAngle() const; - /// Get the current joint angle speed in radians per second. - float32 GetJointSpeed() const; + /// Get the current joint angle speed in radians per second. + float32 GetJointSpeed() const; - /// Is the joint limit enabled? - bool IsLimitEnabled() const; + /// Is the joint limit enabled? + bool IsLimitEnabled() const; - /// Enable/disable the joint limit. - void EnableLimit(bool flag); + /// Enable/disable the joint limit. + void EnableLimit(bool flag); - /// Get the lower joint limit in radians. - float32 GetLowerLimit() const; + /// Get the lower joint limit in radians. + float32 GetLowerLimit() const; - /// Get the upper joint limit in radians. - float32 GetUpperLimit() const; + /// Get the upper joint limit in radians. + float32 GetUpperLimit() const; - /// Set the joint limits in radians. - void SetLimits(float32 lower, float32 upper); + /// Set the joint limits in radians. + void SetLimits(float32 lower, float32 upper); - /// Is the joint motor enabled? - bool IsMotorEnabled() const; + /// Is the joint motor enabled? + bool IsMotorEnabled() const; - /// Enable/disable the joint motor. - void EnableMotor(bool flag); + /// Enable/disable the joint motor. + void EnableMotor(bool flag); - /// Set the motor speed in radians per second. - void SetMotorSpeed(float32 speed); + /// Set the motor speed in radians per second. + void SetMotorSpeed(float32 speed); - /// Get the motor speed in radians per second. - float32 GetMotorSpeed() const; + /// Get the motor speed in radians per second. + float32 GetMotorSpeed() const; - /// Set the maximum motor torque, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } + /// Set the maximum motor torque, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const; + /// Get the reaction force given the inverse time step. + /// Unit is N. + b2Vec2 GetReactionForce(float32 inv_dt) const; - /// Get the reaction torque due to the joint limit given the inverse time step. - /// Unit is N*m. - float32 GetReactionTorque(float32 inv_dt) const; + /// Get the reaction torque due to the joint limit given the inverse time step. + /// Unit is N*m. + float32 GetReactionTorque(float32 inv_dt) const; - /// Get the current motor torque given the inverse time step. - /// Unit is N*m. - float32 GetMotorTorque(float32 inv_dt) const; + /// Get the current motor torque given the inverse time step. + /// Unit is N*m. + float32 GetMotorTorque(float32 inv_dt) const; - /// Dump to b2Log. - void Dump(); + /// Dump to b2Log. + void Dump(); protected: - - friend class b2Joint; - friend class b2GearJoint; + + friend class b2Joint; + friend class b2GearJoint; - b2RevoluteJoint(const b2RevoluteJointDef* def); + b2RevoluteJoint(const b2RevoluteJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec3 m_impulse; - float32 m_motorImpulse; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec3 m_impulse; + float32 m_motorImpulse; - bool m_enableMotor; - float32 m_maxMotorTorque; - float32 m_motorSpeed; + bool m_enableMotor; + float32 m_maxMotorTorque; + float32 m_motorSpeed; - bool m_enableLimit; - float32 m_referenceAngle; - float32 m_lowerAngle; - float32 m_upperAngle; + bool m_enableLimit; + float32 m_referenceAngle; + float32 m_lowerAngle; + float32 m_upperAngle; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; // effective mass for point-to-point constraint. - float32 m_motorMass; // effective mass for motor/limit angular constraint. - b2LimitState m_limitState; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; // effective mass for point-to-point constraint. + float32 m_motorMass; // effective mass for motor/limit angular constraint. + b2LimitState m_limitState; }; inline float32 b2RevoluteJoint::GetMotorSpeed() const { - return m_motorSpeed; + return m_motorSpeed; } #endif diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp index 17a70d9230..952ee7a3e1 100644 --- a/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2RopeJoint.cpp @@ -32,210 +32,210 @@ b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; - m_maxLength = def->maxLength; + m_maxLength = def->maxLength; - m_mass = 0.0f; - m_impulse = 0.0f; - m_state = e_inactiveLimit; - m_length = 0.0f; + m_mass = 0.0f; + m_impulse = 0.0f; + m_state = e_inactiveLimit; + m_length = 0.0f; } void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_u = cB + m_rB - cA - m_rA; - m_length = m_u.Length(); + m_length = m_u.Length(); - float32 C = m_length - m_maxLength; - if (C > 0.0f) - { - m_state = e_atUpperLimit; - } - else - { - m_state = e_inactiveLimit; - } + float32 C = m_length - m_maxLength; + if (C > 0.0f) + { + m_state = e_atUpperLimit; + } + else + { + m_state = e_inactiveLimit; + } - if (m_length > b2_linearSlop) - { - m_u *= 1.0f / m_length; - } - else - { - m_u.SetZero(); - m_mass = 0.0f; - m_impulse = 0.0f; - return; - } + if (m_length > b2_linearSlop) + { + m_u *= 1.0f / m_length; + } + else + { + m_u.SetZero(); + m_mass = 0.0f; + m_impulse = 0.0f; + return; + } - // Compute effective mass. - float32 crA = b2Cross(m_rA, m_u); - float32 crB = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; + // Compute effective mass. + float32 crA = b2Cross(m_rA, m_u); + float32 crB = b2Cross(m_rB, m_u); + float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; + m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale the impulse to support a variable time step. + m_impulse *= data.step.dtRatio; - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } + b2Vec2 P = m_impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); + } + else + { + m_impulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 C = m_length - m_maxLength; - float32 Cdot = b2Dot(m_u, vpB - vpA); + // Cdot = dot(u, v + cross(w, r)) + b2Vec2 vpA = vA + b2Cross(wA, m_rA); + b2Vec2 vpB = vB + b2Cross(wB, m_rB); + float32 C = m_length - m_maxLength; + float32 Cdot = b2Dot(m_u, vpB - vpA); - // Predictive constraint. - if (C < 0.0f) - { - Cdot += data.step.inv_dt * C; - } + // Predictive constraint. + if (C < 0.0f) + { + Cdot += data.step.inv_dt * C; + } - float32 impulse = -m_mass * Cdot; - float32 oldImpulse = m_impulse; - m_impulse = b2Min(0.0f, m_impulse + impulse); - impulse = m_impulse - oldImpulse; + float32 impulse = -m_mass * Cdot; + float32 oldImpulse = m_impulse; + m_impulse = b2Min(0.0f, m_impulse + impulse); + impulse = m_impulse - oldImpulse; - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); + b2Vec2 P = impulse * m_u; + vA -= m_invMassA * P; + wA -= m_invIA * b2Cross(m_rA, P); + vB += m_invMassB * P; + wB += m_invIB * b2Cross(m_rB, P); - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 u = cB + rB - cA - rA; - float32 length = u.Normalize(); - float32 C = length - m_maxLength; + float32 length = u.Normalize(); + float32 C = length - m_maxLength; - C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); + C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; + float32 impulse = -m_mass * C; + b2Vec2 P = impulse * u; - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); + cA -= m_invMassA * P; + aA -= m_invIA * b2Cross(rA, P); + cB += m_invMassB * P; + aB += m_invIB * b2Cross(rB, P); - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return length - m_maxLength < b2_linearSlop; + return length - m_maxLength < b2_linearSlop; } b2Vec2 b2RopeJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RopeJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; + b2Vec2 F = (inv_dt * m_impulse) * m_u; + return F; } float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const { - B2_NOT_USED(inv_dt); - return 0.0f; + B2_NOT_USED(inv_dt); + return 0.0f; } float32 b2RopeJoint::GetMaxLength() const { - return m_maxLength; + return m_maxLength; } b2LimitState b2RopeJoint::GetLimitState() const { - return m_state; + return m_state; } void b2RopeJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2RopeJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2RopeJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2RopeJoint.h b/external/Box2D/Dynamics/Joints/b2RopeJoint.h index d7091b6650..eaca575d06 100644 --- a/external/Box2D/Dynamics/Joints/b2RopeJoint.h +++ b/external/Box2D/Dynamics/Joints/b2RopeJoint.h @@ -27,24 +27,24 @@ /// see collideConnected in b2JointDef. struct b2RopeJointDef : public b2JointDef { - b2RopeJointDef() - { - type = e_ropeJoint; - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - maxLength = 0.0f; - } + b2RopeJointDef() + { + type = e_ropeJoint; + localAnchorA.Set(-1.0f, 0.0f); + localAnchorB.Set(1.0f, 0.0f); + maxLength = 0.0f; + } - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The maximum length of the rope. - /// Warning: this must be larger than b2_linearSlop or - /// the joint will have no effect. - float32 maxLength; + /// The maximum length of the rope. + /// Warning: this must be larger than b2_linearSlop or + /// the joint will have no effect. + float32 maxLength; }; /// A rope joint enforces a maximum distance between two points @@ -58,57 +58,57 @@ struct b2RopeJointDef : public b2JointDef class b2RopeJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// Set/Get the maximum length of the rope. - void SetMaxLength(float32 length) { m_maxLength = length; } - float32 GetMaxLength() const; + /// Set/Get the maximum length of the rope. + void SetMaxLength(float32 length) { m_maxLength = length; } + float32 GetMaxLength() const; - b2LimitState GetLimitState() const; + b2LimitState GetLimitState() const; - /// Dump joint to dmLog - void Dump(); + /// Dump joint to dmLog + void Dump(); protected: - friend class b2Joint; - b2RopeJoint(const b2RopeJointDef* data); + friend class b2Joint; + b2RopeJoint(const b2RopeJointDef* data); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_maxLength; - float32 m_length; - float32 m_impulse; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_maxLength; + float32 m_length; + float32 m_impulse; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; - b2LimitState m_state; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_u; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + float32 m_mass; + b2LimitState m_state; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp index f50bdd6587..253f7216ef 100644 --- a/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2WeldJoint.cpp @@ -36,295 +36,293 @@ void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_referenceAngle = def->referenceAngle; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; - m_impulse.SetZero(); + m_impulse.SetZero(); } void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] + // J = [-I -r1_skew I r2_skew] + // [ 0 -1 0 1] + // r_skew = [-ry; rx] - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + // Matlab + // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] + // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] + // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Mat33 K; - K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - K.ez.x = -m_rA.y * iA - m_rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - K.ez.y = m_rA.x * iA + m_rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; + b2Mat33 K; + K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; + K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; + K.ez.x = -m_rA.y * iA - m_rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; + K.ez.y = m_rA.x * iA + m_rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; - if (m_frequencyHz > 0.0f) - { - K.GetInverse22(&m_mass); + if (m_frequencyHz > 0.0f) + { + K.GetInverse22(&m_mass); - float32 invM = iA + iB; - float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; + float32 invM = iA + iB; + float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; - float32 C = aB - aA - m_referenceAngle; + float32 C = aB - aA - m_referenceAngle; - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; - // Damping coefficient - float32 d = 2.0f * m * m_dampingRatio * omega; + // Damping coefficient + float32 d = 2.0f * m * m_dampingRatio * omega; - // Spring stiffness - float32 k = m * omega * omega; + // Spring stiffness + float32 k = m * omega * omega; - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; + m_bias = C * h * k * m_gamma; - invM += m_gamma; - m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; - } - else - { - K.GetSymInverse33(&m_mass); - m_gamma = 0.0f; - m_bias = 0.0f; - } + invM += m_gamma; + m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; + } + else + { + K.GetSymInverse33(&m_mass); + m_gamma = 0.0f; + m_bias = 0.0f; + } - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Scale impulses to support a variable time step. + m_impulse *= data.step.dtRatio; - b2Vec2 P(m_impulse.x, m_impulse.y); + b2Vec2 P(m_impulse.x, m_impulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_impulse.z); - } - else - { - m_impulse.SetZero(); - } + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + m_impulse.z); + } + else + { + m_impulse.SetZero(); + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) { - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - if (m_frequencyHz > 0.0f) - { - float32 Cdot2 = wB - wA; + if (m_frequencyHz > 0.0f) + { + float32 Cdot2 = wB - wA; - float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); - m_impulse.z += impulse2; + float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); + m_impulse.z += impulse2; - wA -= iA * impulse2; - wB += iB * impulse2; + wA -= iA * impulse2; + wB += iB * impulse2; - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); - m_impulse.x += impulse1.x; - m_impulse.y += impulse1.y; + b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); + m_impulse.x += impulse1.x; + m_impulse.y += impulse1.y; - b2Vec2 P = impulse1; + b2Vec2 P = impulse1; - vA -= mA * P; - wA -= iA * b2Cross(m_rA, P); + vA -= mA * P; + wA -= iA * b2Cross(m_rA, P); - vB += mB * P; - wB += iB * b2Cross(m_rB, P); - } - else - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); + vB += mB * P; + wB += iB * b2Cross(m_rB, P); + } + else + { + b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); + float32 Cdot2 = wB - wA; + b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - b2Vec3 impulse = -b2Mul(m_mass, Cdot); - m_impulse += impulse; + b2Vec3 impulse = -b2Mul(m_mass, Cdot); + m_impulse += impulse; - b2Vec2 P(impulse.x, impulse.y); + b2Vec2 P(impulse.x, impulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); + vA -= mA * P; + wA -= iA * (b2Cross(m_rA, P) + impulse.z); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } + vB += mB * P; + wB += iB * (b2Cross(m_rB, P) + impulse.z); + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - float32 positionError, angularError; + float32 positionError, angularError; - b2Mat33 K; - K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - K.ez.x = -rA.y * iA - rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - K.ez.y = rA.x * iA + rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; + b2Mat33 K; + K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; + K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; + K.ez.x = -rA.y * iA - rB.y * iB; + K.ex.y = K.ey.x; + K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; + K.ez.y = rA.x * iA + rB.x * iB; + K.ex.z = K.ez.x; + K.ey.z = K.ez.y; + K.ez.z = iA + iB; - if (m_frequencyHz > 0.0f) - { - b2Vec2 C1 = cB + rB - cA - rA; + if (m_frequencyHz > 0.0f) + { + b2Vec2 C1 = cB + rB - cA - rA; - positionError = C1.Length(); - angularError = 0.0f; + positionError = C1.Length(); + angularError = 0.0f; - b2Vec2 P = -K.Solve22(C1); + b2Vec2 P = -K.Solve22(C1); - cA -= mA * P; - aA -= iA * b2Cross(rA, P); + cA -= mA * P; + aA -= iA * b2Cross(rA, P); - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - else - { - b2Vec2 C1 = cB + rB - cA - rA; - float32 C2 = aB - aA - m_referenceAngle; + cB += mB * P; + aB += iB * b2Cross(rB, P); + } + else + { + b2Vec2 C1 = cB + rB - cA - rA; + float32 C2 = aB - aA - m_referenceAngle; - positionError = C1.Length(); - angularError = b2Abs(C2); + positionError = C1.Length(); + angularError = b2Abs(C2); - b2Vec3 C(C1.x, C1.y, C2); - - b2Vec3 impulse = -K.Solve33(C); - b2Vec2 P(impulse.x, impulse.y); + b2Vec3 C(C1.x, C1.y, C2); + + b2Vec3 impulse = -K.Solve33(C); + b2Vec2 P(impulse.x, impulse.y); - cA -= mA * P; - aA -= iA * (b2Cross(rA, P) + impulse.z); + cA -= mA * P; + aA -= iA * (b2Cross(rA, P) + impulse.z); - cB += mB * P; - aB += iB * (b2Cross(rB, P) + impulse.z); - } + cB += mB * P; + aB += iB * (b2Cross(rB, P) + impulse.z); + } - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; + return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2WeldJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2WeldJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const { - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; + b2Vec2 P(m_impulse.x, m_impulse.y); + return inv_dt * P; } float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * m_impulse.z; + return inv_dt * m_impulse.z; } void b2WeldJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2WeldJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2WeldJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2WeldJoint.h b/external/Box2D/Dynamics/Joints/b2WeldJoint.h index 751c6a8770..eed9bc1032 100644 --- a/external/Box2D/Dynamics/Joints/b2WeldJoint.h +++ b/external/Box2D/Dynamics/Joints/b2WeldJoint.h @@ -26,35 +26,35 @@ /// of the anchor points is important for computing the reaction torque. struct b2WeldJointDef : public b2JointDef { - b2WeldJointDef() - { - type = e_weldJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } + b2WeldJointDef() + { + type = e_weldJoint; + localAnchorA.Set(0.0f, 0.0f); + localAnchorB.Set(0.0f, 0.0f); + referenceAngle = 0.0f; + frequencyHz = 0.0f; + dampingRatio = 0.0f; + } - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); + /// Initialize the bodies, anchors, and reference angle using a world + /// anchor point. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// The mass-spring-damper frequency in Hertz. Rotation only. - /// Disable softness with a value of 0. - float32 frequencyHz; + /// The bodyB angle minus bodyA angle in the reference state (radians). + float32 referenceAngle; + + /// The mass-spring-damper frequency in Hertz. Rotation only. + /// Disable softness with a value of 0. + float32 frequencyHz; - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; + /// The damping ratio. 0 = no damping, 1 = critical damping. + float32 dampingRatio; }; /// A weld joint essentially glues two bodies together. A weld joint may @@ -62,65 +62,65 @@ struct b2WeldJointDef : public b2JointDef class b2WeldJoint : public b2Joint { public: - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } + /// Get the reference angle. + float32 GetReferenceAngle() const { return m_referenceAngle; } - /// Set/get frequency in Hz. - void SetFrequency(float32 hz) { m_frequencyHz = hz; } - float32 GetFrequency() const { return m_frequencyHz; } + /// Set/get frequency in Hz. + void SetFrequency(float32 hz) { m_frequencyHz = hz; } + float32 GetFrequency() const { return m_frequencyHz; } - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } - float32 GetDampingRatio() const { return m_dampingRatio; } + /// Set/get damping ratio. + void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } + float32 GetDampingRatio() const { return m_dampingRatio; } - /// Dump to b2Log - void Dump(); + /// Dump to b2Log + void Dump(); protected: - friend class b2Joint; + friend class b2Joint; - b2WeldJoint(const b2WeldJointDef* def); + b2WeldJoint(const b2WeldJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; + float32 m_frequencyHz; + float32 m_dampingRatio; + float32 m_bias; - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_referenceAngle; - float32 m_gamma; - b2Vec3 m_impulse; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + float32 m_referenceAngle; + float32 m_gamma; + b2Vec3 m_impulse; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_rA; + b2Vec2 m_rB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; + b2Mat33 m_mass; }; #endif diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp index 6253437706..c9f6de6005 100644 --- a/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp +++ b/external/Box2D/Dynamics/Joints/b2WheelJoint.cpp @@ -38,382 +38,382 @@ void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) { - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); + bodyA = bA; + bodyB = bB; + localAnchorA = bodyA->GetLocalPoint(anchor); + localAnchorB = bodyB->GetLocalPoint(anchor); + localAxisA = bodyA->GetLocalVector(axis); } b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) : b2Joint(def) { - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); + m_localAnchorA = def->localAnchorA; + m_localAnchorB = def->localAnchorB; + m_localXAxisA = def->localAxisA; + m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_mass = 0.0f; - m_impulse = 0.0f; - m_motorMass = 0.0; - m_motorImpulse = 0.0f; - m_springMass = 0.0f; - m_springImpulse = 0.0f; + m_mass = 0.0f; + m_impulse = 0.0f; + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; + m_springMass = 0.0f; + m_springImpulse = 0.0f; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableMotor = def->enableMotor; + m_maxMotorTorque = def->maxMotorTorque; + m_motorSpeed = def->motorSpeed; + m_enableMotor = def->enableMotor; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; + m_frequencyHz = def->frequencyHz; + m_dampingRatio = def->dampingRatio; - m_bias = 0.0f; - m_gamma = 0.0f; + m_bias = 0.0f; + m_gamma = 0.0f; - m_ax.SetZero(); - m_ay.SetZero(); + m_ax.SetZero(); + m_ay.SetZero(); } void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) { - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; + m_indexA = m_bodyA->m_islandIndex; + m_indexB = m_bodyB->m_islandIndex; + m_localCenterA = m_bodyA->m_sweep.localCenter; + m_localCenterB = m_bodyB->m_sweep.localCenter; + m_invMassA = m_bodyA->m_invMass; + m_invMassB = m_bodyB->m_invMass; + m_invIA = m_bodyA->m_invI; + m_invIB = m_bodyB->m_invI; - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; + // Compute the effective masses. + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = cB + rB - cA - rA; - // Point to line constraint - { - m_ay = b2Mul(qA, m_localYAxisA); - m_sAy = b2Cross(d + rA, m_ay); - m_sBy = b2Cross(rB, m_ay); + // Point to line constraint + { + m_ay = b2Mul(qA, m_localYAxisA); + m_sAy = b2Cross(d + rA, m_ay); + m_sBy = b2Cross(rB, m_ay); - m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; + m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - } + if (m_mass > 0.0f) + { + m_mass = 1.0f / m_mass; + } + } - // Spring constraint - m_springMass = 0.0f; - m_bias = 0.0f; - m_gamma = 0.0f; - if (m_frequencyHz > 0.0f) - { - m_ax = b2Mul(qA, m_localXAxisA); - m_sAx = b2Cross(d + rA, m_ax); - m_sBx = b2Cross(rB, m_ax); + // Spring constraint + m_springMass = 0.0f; + m_bias = 0.0f; + m_gamma = 0.0f; + if (m_frequencyHz > 0.0f) + { + m_ax = b2Mul(qA, m_localXAxisA); + m_sAx = b2Cross(d + rA, m_ax); + m_sBx = b2Cross(rB, m_ax); - float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; + float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; - if (invMass > 0.0f) - { - m_springMass = 1.0f / invMass; + if (invMass > 0.0f) + { + m_springMass = 1.0f / invMass; - float32 C = b2Dot(d, m_ax); + float32 C = b2Dot(d, m_ax); - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; + // Frequency + float32 omega = 2.0f * b2_pi * m_frequencyHz; - // Damping coefficient - float32 d = 2.0f * m_springMass * m_dampingRatio * omega; + // Damping coefficient + float32 d = 2.0f * m_springMass * m_dampingRatio * omega; - // Spring stiffness - float32 k = m_springMass * omega * omega; + // Spring stiffness + float32 k = m_springMass * omega * omega; - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - if (m_gamma > 0.0f) - { - m_gamma = 1.0f / m_gamma; - } + // magic formulas + float32 h = data.step.dt; + m_gamma = h * (d + h * k); + if (m_gamma > 0.0f) + { + m_gamma = 1.0f / m_gamma; + } - m_bias = C * h * k * m_gamma; + m_bias = C * h * k * m_gamma; - m_springMass = invMass + m_gamma; - if (m_springMass > 0.0f) - { - m_springMass = 1.0f / m_springMass; - } - } - } - else - { - m_springImpulse = 0.0f; - } + m_springMass = invMass + m_gamma; + if (m_springMass > 0.0f) + { + m_springMass = 1.0f / m_springMass; + } + } + } + else + { + m_springImpulse = 0.0f; + } - // Rotational motor - if (m_enableMotor) - { - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - else - { - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - } + // Rotational motor + if (m_enableMotor) + { + m_motorMass = iA + iB; + if (m_motorMass > 0.0f) + { + m_motorMass = 1.0f / m_motorMass; + } + } + else + { + m_motorMass = 0.0f; + m_motorImpulse = 0.0f; + } - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_springImpulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; + if (data.step.warmStarting) + { + // Account for variable time step. + m_impulse *= data.step.dtRatio; + m_springImpulse *= data.step.dtRatio; + m_motorImpulse *= data.step.dtRatio; - b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; - float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; - float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; + b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; + float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; + float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; - vA -= m_invMassA * P; - wA -= m_invIA * LA; + vA -= m_invMassA * P; + wA -= m_invIA * LA; - vB += m_invMassB * P; - wB += m_invIB * LB; - } - else - { - m_impulse = 0.0f; - m_springImpulse = 0.0f; - m_motorImpulse = 0.0f; - } + vB += m_invMassB * P; + wB += m_invIB * LB; + } + else + { + m_impulse = 0.0f; + m_springImpulse = 0.0f; + m_motorImpulse = 0.0f; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) { - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; + float32 mA = m_invMassA, mB = m_invMassB; + float32 iA = m_invIA, iB = m_invIB; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; + b2Vec2 vA = data.velocities[m_indexA].v; + float32 wA = data.velocities[m_indexA].w; + b2Vec2 vB = data.velocities[m_indexB].v; + float32 wB = data.velocities[m_indexB].w; - // Solve spring constraint - { - float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; - float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); - m_springImpulse += impulse; + // Solve spring constraint + { + float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; + float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); + m_springImpulse += impulse; - b2Vec2 P = impulse * m_ax; - float32 LA = impulse * m_sAx; - float32 LB = impulse * m_sBx; + b2Vec2 P = impulse * m_ax; + float32 LA = impulse * m_sAx; + float32 LB = impulse * m_sBx; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; - } + vB += mB * P; + wB += iB * LB; + } - // Solve rotational motor constraint - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; + // Solve rotational motor constraint + { + float32 Cdot = wB - wA - m_motorSpeed; + float32 impulse = -m_motorMass * Cdot; - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; + float32 oldImpulse = m_motorImpulse; + float32 maxImpulse = data.step.dt * m_maxMotorTorque; + m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); + impulse = m_motorImpulse - oldImpulse; - wA -= iA * impulse; - wB += iB * impulse; - } + wA -= iA * impulse; + wB += iB * impulse; + } - // Solve point to line constraint - { - float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; + // Solve point to line constraint + { + float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; + float32 impulse = -m_mass * Cdot; + m_impulse += impulse; - b2Vec2 P = impulse * m_ay; - float32 LA = impulse * m_sAy; - float32 LB = impulse * m_sBy; + b2Vec2 P = impulse * m_ay; + float32 LA = impulse * m_sAy; + float32 LB = impulse * m_sBy; - vA -= mA * P; - wA -= iA * LA; + vA -= mA * P; + wA -= iA * LA; - vB += mB * P; - wB += iB * LB; - } + vB += mB * P; + wB += iB * LB; + } - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; + data.velocities[m_indexA].v = vA; + data.velocities[m_indexA].w = wA; + data.velocities[m_indexB].v = vB; + data.velocities[m_indexB].w = wB; } bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) { - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; + b2Vec2 cA = data.positions[m_indexA].c; + float32 aA = data.positions[m_indexA].a; + b2Vec2 cB = data.positions[m_indexB].c; + float32 aB = data.positions[m_indexB].a; - b2Rot qA(aA), qB(aB); + b2Rot qA(aA), qB(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; + b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); + b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); + b2Vec2 d = (cB - cA) + rB - rA; - b2Vec2 ay = b2Mul(qA, m_localYAxisA); + b2Vec2 ay = b2Mul(qA, m_localYAxisA); - float32 sAy = b2Cross(d + rA, ay); - float32 sBy = b2Cross(rB, ay); + float32 sAy = b2Cross(d + rA, ay); + float32 sBy = b2Cross(rB, ay); - float32 C = b2Dot(d, ay); + float32 C = b2Dot(d, ay); - float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; + float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; - float32 impulse; - if (k != 0.0f) - { - impulse = - C / k; - } - else - { - impulse = 0.0f; - } + float32 impulse; + if (k != 0.0f) + { + impulse = - C / k; + } + else + { + impulse = 0.0f; + } - b2Vec2 P = impulse * ay; - float32 LA = impulse * sAy; - float32 LB = impulse * sBy; + b2Vec2 P = impulse * ay; + float32 LA = impulse * sAy; + float32 LB = impulse * sBy; - cA -= m_invMassA * P; - aA -= m_invIA * LA; - cB += m_invMassB * P; - aB += m_invIB * LB; + cA -= m_invMassA * P; + aA -= m_invIA * LA; + cB += m_invMassB * P; + aB += m_invIB * LB; - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; + data.positions[m_indexA].c = cA; + data.positions[m_indexA].a = aA; + data.positions[m_indexB].c = cB; + data.positions[m_indexB].a = aB; - return b2Abs(C) <= b2_linearSlop; + return b2Abs(C) <= b2_linearSlop; } b2Vec2 b2WheelJoint::GetAnchorA() const { - return m_bodyA->GetWorldPoint(m_localAnchorA); + return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2WheelJoint::GetAnchorB() const { - return m_bodyB->GetWorldPoint(m_localAnchorB); + return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const { - return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); + return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); } float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const { - return inv_dt * m_motorImpulse; + return inv_dt * m_motorImpulse; } float32 b2WheelJoint::GetJointTranslation() const { - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; + b2Body* bA = m_bodyA; + b2Body* bB = m_bodyB; - b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); + b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); + b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); + b2Vec2 d = pB - pA; + b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); - float32 translation = b2Dot(d, axis); - return translation; + float32 translation = b2Dot(d, axis); + return translation; } float32 b2WheelJoint::GetJointSpeed() const { - float32 wA = m_bodyA->m_angularVelocity; - float32 wB = m_bodyB->m_angularVelocity; - return wB - wA; + float32 wA = m_bodyA->m_angularVelocity; + float32 wB = m_bodyB->m_angularVelocity; + return wB - wA; } bool b2WheelJoint::IsMotorEnabled() const { - return m_enableMotor; + return m_enableMotor; } void b2WheelJoint::EnableMotor(bool flag) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_enableMotor = flag; } void b2WheelJoint::SetMotorSpeed(float32 speed) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_motorSpeed = speed; } void b2WheelJoint::SetMaxMotorTorque(float32 torque) { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; + m_bodyA->SetAwake(true); + m_bodyB->SetAwake(true); + m_maxMotorTorque = torque; } float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const { - return inv_dt * m_motorImpulse; + return inv_dt * m_motorImpulse; } void b2WheelJoint::Dump() { - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; + int32 indexA = m_bodyA->m_islandIndex; + int32 indexB = m_bodyB->m_islandIndex; - b2Log(" b2WheelJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); + b2Log(" b2WheelJointDef jd;\n"); + b2Log(" jd.bodyA = bodies[%d];\n", indexA); + b2Log(" jd.bodyB = bodies[%d];\n", indexB); + b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); + b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); + b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); + b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); + b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); + b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); + b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); + b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); + b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); + b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } diff --git a/external/Box2D/Dynamics/Joints/b2WheelJoint.h b/external/Box2D/Dynamics/Joints/b2WheelJoint.h index ede1b08b7c..ca59d7a64a 100644 --- a/external/Box2D/Dynamics/Joints/b2WheelJoint.h +++ b/external/Box2D/Dynamics/Joints/b2WheelJoint.h @@ -29,46 +29,46 @@ /// anchors and a local axis helps when saving and loading a game. struct b2WheelJointDef : public b2JointDef { - b2WheelJointDef() - { - type = e_wheelJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - enableMotor = false; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - frequencyHz = 2.0f; - dampingRatio = 0.7f; - } + b2WheelJointDef() + { + type = e_wheelJoint; + localAnchorA.SetZero(); + localAnchorB.SetZero(); + localAxisA.Set(1.0f, 0.0f); + enableMotor = false; + maxMotorTorque = 0.0f; + motorSpeed = 0.0f; + frequencyHz = 2.0f; + dampingRatio = 0.7f; + } - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); + /// Initialize the bodies, anchors, axis, and reference angle using the world + /// anchor and world axis. + void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; + /// The local anchor point relative to bodyA's origin. + b2Vec2 localAnchorA; - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; + /// The local anchor point relative to bodyB's origin. + b2Vec2 localAnchorB; - /// The local translation axis in bodyA. - b2Vec2 localAxisA; + /// The local translation axis in bodyA. + b2Vec2 localAxisA; - /// Enable/disable the joint motor. - bool enableMotor; + /// Enable/disable the joint motor. + bool enableMotor; - /// The maximum motor torque, usually in N-m. - float32 maxMotorTorque; + /// The maximum motor torque, usually in N-m. + float32 maxMotorTorque; - /// The desired motor speed in radians per second. - float32 motorSpeed; + /// The desired motor speed in radians per second. + float32 motorSpeed; - /// Suspension frequency, zero indicates no suspension - float32 frequencyHz; + /// Suspension frequency, zero indicates no suspension + float32 frequencyHz; - /// Suspension damping ratio, one indicates critical damping - float32 dampingRatio; + /// Suspension damping ratio, one indicates critical damping + float32 dampingRatio; }; /// A wheel joint. This joint provides two degrees of freedom: translation @@ -79,135 +79,133 @@ struct b2WheelJointDef : public b2JointDef class b2WheelJoint : public b2Joint { public: - void GetDefinition(b2WheelJointDef* def) const; + b2Vec2 GetAnchorA() const; + b2Vec2 GetAnchorB() const; - b2Vec2 GetAnchorA() const; - b2Vec2 GetAnchorB() const; + b2Vec2 GetReactionForce(float32 inv_dt) const; + float32 GetReactionTorque(float32 inv_dt) const; - b2Vec2 GetReactionForce(float32 inv_dt) const; - float32 GetReactionTorque(float32 inv_dt) const; + /// The local anchor point relative to bodyA's origin. + const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } + /// The local anchor point relative to bodyB's origin. + const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } + /// The local joint axis relative to bodyA. + const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } + /// Get the current joint translation, usually in meters. + float32 GetJointTranslation() const; - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; + /// Get the current joint translation speed, usually in meters per second. + float32 GetJointSpeed() const; - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; + /// Is the joint motor enabled? + bool IsMotorEnabled() const; - /// Is the joint motor enabled? - bool IsMotorEnabled() const; + /// Enable/disable the joint motor. + void EnableMotor(bool flag); - /// Enable/disable the joint motor. - void EnableMotor(bool flag); + /// Set the motor speed, usually in radians per second. + void SetMotorSpeed(float32 speed); - /// Set the motor speed, usually in radians per second. - void SetMotorSpeed(float32 speed); + /// Get the motor speed, usually in radians per second. + float32 GetMotorSpeed() const; - /// Get the motor speed, usually in radians per second. - float32 GetMotorSpeed() const; + /// Set/Get the maximum motor force, usually in N-m. + void SetMaxMotorTorque(float32 torque); + float32 GetMaxMotorTorque() const; - /// Set/Get the maximum motor force, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const; + /// Get the current motor torque given the inverse time step, usually in N-m. + float32 GetMotorTorque(float32 inv_dt) const; - /// Get the current motor torque given the inverse time step, usually in N-m. - float32 GetMotorTorque(float32 inv_dt) const; + /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. + void SetSpringFrequencyHz(float32 hz); + float32 GetSpringFrequencyHz() const; - /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. - void SetSpringFrequencyHz(float32 hz); - float32 GetSpringFrequencyHz() const; + /// Set/Get the spring damping ratio + void SetSpringDampingRatio(float32 ratio); + float32 GetSpringDampingRatio() const; - /// Set/Get the spring damping ratio - void SetSpringDampingRatio(float32 ratio); - float32 GetSpringDampingRatio() const; - - /// Dump to b2Log - void Dump(); + /// Dump to b2Log + void Dump(); protected: - friend class b2Joint; - b2WheelJoint(const b2WheelJointDef* def); + friend class b2Joint; + b2WheelJoint(const b2WheelJointDef* def); - void InitVelocityConstraints(const b2SolverData& data); - void SolveVelocityConstraints(const b2SolverData& data); - bool SolvePositionConstraints(const b2SolverData& data); + void InitVelocityConstraints(const b2SolverData& data); + void SolveVelocityConstraints(const b2SolverData& data); + bool SolvePositionConstraints(const b2SolverData& data); - float32 m_frequencyHz; - float32 m_dampingRatio; + float32 m_frequencyHz; + float32 m_dampingRatio; - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; + // Solver shared + b2Vec2 m_localAnchorA; + b2Vec2 m_localAnchorB; + b2Vec2 m_localXAxisA; + b2Vec2 m_localYAxisA; - float32 m_impulse; - float32 m_motorImpulse; - float32 m_springImpulse; + float32 m_impulse; + float32 m_motorImpulse; + float32 m_springImpulse; - float32 m_maxMotorTorque; - float32 m_motorSpeed; - bool m_enableMotor; + float32 m_maxMotorTorque; + float32 m_motorSpeed; + bool m_enableMotor; - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; + // Solver temp + int32 m_indexA; + int32 m_indexB; + b2Vec2 m_localCenterA; + b2Vec2 m_localCenterB; + float32 m_invMassA; + float32 m_invMassB; + float32 m_invIA; + float32 m_invIB; - b2Vec2 m_ax, m_ay; - float32 m_sAx, m_sBx; - float32 m_sAy, m_sBy; + b2Vec2 m_ax, m_ay; + float32 m_sAx, m_sBx; + float32 m_sAy, m_sBy; - float32 m_mass; - float32 m_motorMass; - float32 m_springMass; + float32 m_mass; + float32 m_motorMass; + float32 m_springMass; - float32 m_bias; - float32 m_gamma; + float32 m_bias; + float32 m_gamma; }; inline float32 b2WheelJoint::GetMotorSpeed() const { - return m_motorSpeed; + return m_motorSpeed; } inline float32 b2WheelJoint::GetMaxMotorTorque() const { - return m_maxMotorTorque; + return m_maxMotorTorque; } inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) { - m_frequencyHz = hz; + m_frequencyHz = hz; } inline float32 b2WheelJoint::GetSpringFrequencyHz() const { - return m_frequencyHz; + return m_frequencyHz; } inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) { - m_dampingRatio = ratio; + m_dampingRatio = ratio; } inline float32 b2WheelJoint::GetSpringDampingRatio() const { - return m_dampingRatio; + return m_dampingRatio; } #endif diff --git a/external/Box2D/Dynamics/b2Body.cpp b/external/Box2D/Dynamics/b2Body.cpp index b22b574023..b6550531f9 100644 --- a/external/Box2D/Dynamics/b2Body.cpp +++ b/external/Box2D/Dynamics/b2Body.cpp @@ -24,491 +24,526 @@ b2Body::b2Body(const b2BodyDef* bd, b2World* world) { - b2Assert(bd->position.IsValid()); - b2Assert(bd->linearVelocity.IsValid()); - b2Assert(b2IsValid(bd->angle)); - b2Assert(b2IsValid(bd->angularVelocity)); - b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); - b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); + b2Assert(bd->position.IsValid()); + b2Assert(bd->linearVelocity.IsValid()); + b2Assert(b2IsValid(bd->angle)); + b2Assert(b2IsValid(bd->angularVelocity)); + b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); + b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); - m_flags = 0; + m_flags = 0; - if (bd->bullet) - { - m_flags |= e_bulletFlag; - } - if (bd->fixedRotation) - { - m_flags |= e_fixedRotationFlag; - } - if (bd->allowSleep) - { - m_flags |= e_autoSleepFlag; - } - if (bd->awake) - { - m_flags |= e_awakeFlag; - } - if (bd->active) - { - m_flags |= e_activeFlag; - } + if (bd->bullet) + { + m_flags |= e_bulletFlag; + } + if (bd->fixedRotation) + { + m_flags |= e_fixedRotationFlag; + } + if (bd->allowSleep) + { + m_flags |= e_autoSleepFlag; + } + if (bd->awake) + { + m_flags |= e_awakeFlag; + } + if (bd->active) + { + m_flags |= e_activeFlag; + } - m_world = world; + m_world = world; - m_xf.p = bd->position; - m_xf.q.Set(bd->angle); + m_xf.p = bd->position; + m_xf.q.Set(bd->angle); - m_sweep.localCenter.SetZero(); - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = bd->angle; - m_sweep.a = bd->angle; - m_sweep.alpha0 = 0.0f; + m_sweep.localCenter.SetZero(); + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = bd->angle; + m_sweep.a = bd->angle; + m_sweep.alpha0 = 0.0f; - m_jointList = NULL; - m_contactList = NULL; - m_prev = NULL; - m_next = NULL; + m_jointList = NULL; + m_contactList = NULL; + m_prev = NULL; + m_next = NULL; - m_linearVelocity = bd->linearVelocity; - m_angularVelocity = bd->angularVelocity; + m_linearVelocity = bd->linearVelocity; + m_angularVelocity = bd->angularVelocity; - m_linearDamping = bd->linearDamping; - m_angularDamping = bd->angularDamping; - m_gravityScale = bd->gravityScale; + m_linearDamping = bd->linearDamping; + m_angularDamping = bd->angularDamping; + m_gravityScale = bd->gravityScale; - m_force.SetZero(); - m_torque = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; - m_sleepTime = 0.0f; + m_sleepTime = 0.0f; - m_type = bd->type; + m_type = bd->type; - if (m_type == b2_dynamicBody) - { - m_mass = 1.0f; - m_invMass = 1.0f; - } - else - { - m_mass = 0.0f; - m_invMass = 0.0f; - } + if (m_type == b2_dynamicBody) + { + m_mass = 1.0f; + m_invMass = 1.0f; + } + else + { + m_mass = 0.0f; + m_invMass = 0.0f; + } - m_I = 0.0f; - m_invI = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; - m_userData = bd->userData; + m_userData = bd->userData; - m_fixtureList = NULL; - m_fixtureCount = 0; + m_fixtureList = NULL; + m_fixtureCount = 0; } b2Body::~b2Body() { - // shapes and joints are destroyed in b2World::Destroy + // shapes and joints are destroyed in b2World::Destroy } void b2Body::SetType(b2BodyType type) { - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } - if (m_type == type) - { - return; - } + if (m_type == type) + { + return; + } - m_type = type; + m_type = type; - ResetMassData(); + ResetMassData(); - if (m_type == b2_staticBody) - { - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_sweep.a0 = m_sweep.a; - m_sweep.c0 = m_sweep.c; - SynchronizeFixtures(); - } + if (m_type == b2_staticBody) + { + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_sweep.a0 = m_sweep.a; + m_sweep.c0 = m_sweep.c; + SynchronizeFixtures(); + } - SetAwake(true); + SetAwake(true); - m_force.SetZero(); - m_torque = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; - // Since the body type changed, we need to flag contacts for filtering. - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Refilter(); - } + // Delete the attached contacts. + b2ContactEdge* ce = m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_world->m_contactManager.Destroy(ce0->contact); + } + m_contactList = NULL; + + // Touch the proxies so that new contacts will be created (when appropriate) + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + int32 proxyCount = f->m_proxyCount; + for (int32 i = 0; i < proxyCount; ++i) + { + broadPhase->TouchProxy(f->m_proxies[i].proxyId); + } + } } b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) { - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return NULL; - } + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return NULL; + } - b2BlockAllocator* allocator = &m_world->m_blockAllocator; + b2BlockAllocator* allocator = &m_world->m_blockAllocator; - void* memory = allocator->Allocate(sizeof(b2Fixture)); - b2Fixture* fixture = new (memory) b2Fixture; - fixture->Create(allocator, this, def); + void* memory = allocator->Allocate(sizeof(b2Fixture)); + b2Fixture* fixture = new (memory) b2Fixture; + fixture->Create(allocator, this, def); - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->CreateProxies(broadPhase, m_xf); - } + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->CreateProxies(broadPhase, m_xf); + } - fixture->m_next = m_fixtureList; - m_fixtureList = fixture; - ++m_fixtureCount; + fixture->m_next = m_fixtureList; + m_fixtureList = fixture; + ++m_fixtureCount; - fixture->m_body = this; + fixture->m_body = this; - // Adjust mass properties if needed. - if (fixture->m_density > 0.0f) - { - ResetMassData(); - } + // Adjust mass properties if needed. + if (fixture->m_density > 0.0f) + { + ResetMassData(); + } - // Let the world know we have a new fixture. This will cause new contacts - // to be created at the beginning of the next time step. - m_world->m_flags |= b2World::e_newFixture; + // Let the world know we have a new fixture. This will cause new contacts + // to be created at the beginning of the next time step. + m_world->m_flags |= b2World::e_newFixture; - return fixture; + return fixture; } b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) { - b2FixtureDef def; - def.shape = shape; - def.density = density; + b2FixtureDef def; + def.shape = shape; + def.density = density; - return CreateFixture(&def); + return CreateFixture(&def); } void b2Body::DestroyFixture(b2Fixture* fixture) { - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } - b2Assert(fixture->m_body == this); + b2Assert(fixture->m_body == this); - // Remove the fixture from this body's singly linked list. - b2Assert(m_fixtureCount > 0); - b2Fixture** node = &m_fixtureList; - bool found = false; - while (*node != NULL) - { - if (*node == fixture) - { - *node = fixture->m_next; - found = true; - break; - } + // Remove the fixture from this body's singly linked list. + b2Assert(m_fixtureCount > 0); + b2Fixture** node = &m_fixtureList; + bool found = false; + while (*node != NULL) + { + if (*node == fixture) + { + *node = fixture->m_next; + found = true; + break; + } - node = &(*node)->m_next; - } + node = &(*node)->m_next; + } - // You tried to remove a shape that is not attached to this body. - b2Assert(found); + // You tried to remove a shape that is not attached to this body. + b2Assert(found); - // Destroy any contacts associated with the fixture. - b2ContactEdge* edge = m_contactList; - while (edge) - { - b2Contact* c = edge->contact; - edge = edge->next; + // Destroy any contacts associated with the fixture. + b2ContactEdge* edge = m_contactList; + while (edge) + { + b2Contact* c = edge->contact; + edge = edge->next; - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); - if (fixture == fixtureA || fixture == fixtureB) - { - // This destroys the contact and removes it from - // this body's contact list. - m_world->m_contactManager.Destroy(c); - } - } + if (fixture == fixtureA || fixture == fixtureB) + { + // This destroys the contact and removes it from + // this body's contact list. + m_world->m_contactManager.Destroy(c); + } + } - b2BlockAllocator* allocator = &m_world->m_blockAllocator; + b2BlockAllocator* allocator = &m_world->m_blockAllocator; - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->DestroyProxies(broadPhase); - } + if (m_flags & e_activeFlag) + { + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + fixture->DestroyProxies(broadPhase); + } - fixture->Destroy(allocator); - fixture->m_body = NULL; - fixture->m_next = NULL; - fixture->~b2Fixture(); - allocator->Free(fixture, sizeof(b2Fixture)); + fixture->Destroy(allocator); + fixture->m_body = NULL; + fixture->m_next = NULL; + fixture->~b2Fixture(); + allocator->Free(fixture, sizeof(b2Fixture)); - --m_fixtureCount; + --m_fixtureCount; - // Reset the mass data. - ResetMassData(); + // Reset the mass data. + ResetMassData(); } void b2Body::ResetMassData() { - // Compute mass data from shapes. Each shape has its own density. - m_mass = 0.0f; - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - m_sweep.localCenter.SetZero(); + // Compute mass data from shapes. Each shape has its own density. + m_mass = 0.0f; + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; + m_sweep.localCenter.SetZero(); - // Static and kinematic bodies have zero mass. - if (m_type == b2_staticBody || m_type == b2_kinematicBody) - { - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = m_sweep.a; - return; - } + // Static and kinematic bodies have zero mass. + if (m_type == b2_staticBody || m_type == b2_kinematicBody) + { + m_sweep.c0 = m_xf.p; + m_sweep.c = m_xf.p; + m_sweep.a0 = m_sweep.a; + return; + } - b2Assert(m_type == b2_dynamicBody); + b2Assert(m_type == b2_dynamicBody); - // Accumulate mass over all fixtures. - b2Vec2 localCenter = b2Vec2_zero; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - if (f->m_density == 0.0f) - { - continue; - } + // Accumulate mass over all fixtures. + b2Vec2 localCenter = b2Vec2_zero; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + if (f->m_density == 0.0f) + { + continue; + } - b2MassData massData; - f->GetMassData(&massData); - m_mass += massData.mass; - localCenter += massData.mass * massData.center; - m_I += massData.I; - } + b2MassData massData; + f->GetMassData(&massData); + m_mass += massData.mass; + localCenter += massData.mass * massData.center; + m_I += massData.I; + } - // Compute center of mass. - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - localCenter *= m_invMass; - } - else - { - // Force all dynamic bodies to have a positive mass. - m_mass = 1.0f; - m_invMass = 1.0f; - } + // Compute center of mass. + if (m_mass > 0.0f) + { + m_invMass = 1.0f / m_mass; + localCenter *= m_invMass; + } + else + { + // Force all dynamic bodies to have a positive mass. + m_mass = 1.0f; + m_invMass = 1.0f; + } - if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) - { - // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(localCenter, localCenter); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; + if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) + { + // Center the inertia about the center of mass. + m_I -= m_mass * b2Dot(localCenter, localCenter); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; - } - else - { - m_I = 0.0f; - m_invI = 0.0f; - } + } + else + { + m_I = 0.0f; + m_invI = 0.0f; + } - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = localCenter; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = localCenter; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); } void b2Body::SetMassData(const b2MassData* massData) { - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; + m_invMass = 0.0f; + m_I = 0.0f; + m_invI = 0.0f; - m_mass = massData->mass; - if (m_mass <= 0.0f) - { - m_mass = 1.0f; - } + m_mass = massData->mass; + if (m_mass <= 0.0f) + { + m_mass = 1.0f; + } - m_invMass = 1.0f / m_mass; + m_invMass = 1.0f / m_mass; - if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - } + if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) + { + m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); + b2Assert(m_I > 0.0f); + m_invI = 1.0f / m_I; + } - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = massData->center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + // Move center of mass. + b2Vec2 oldCenter = m_sweep.c; + m_sweep.localCenter = massData->center; + m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); + // Update center of mass velocity. + m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); } bool b2Body::ShouldCollide(const b2Body* other) const { - // At least one body should be dynamic. - if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) - { - return false; - } + // At least one body should be dynamic. + if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) + { + return false; + } - // Does a joint prevent collision? - for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) - { - if (jn->other == other) - { - if (jn->joint->m_collideConnected == false) - { - return false; - } - } - } + // Does a joint prevent collision? + for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) + { + if (jn->other == other) + { + if (jn->joint->m_collideConnected == false) + { + return false; + } + } + } - return true; + return true; } void b2Body::SetTransform(const b2Vec2& position, float32 angle) { - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } + b2Assert(m_world->IsLocked() == false); + if (m_world->IsLocked() == true) + { + return; + } - m_xf.q.Set(angle); - m_xf.p = position; + m_xf.q.Set(angle); + m_xf.p = position; - m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a = angle; + m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); + m_sweep.a = angle; - m_sweep.c0 = m_sweep.c; - m_sweep.a0 = angle; + m_sweep.c0 = m_sweep.c; + m_sweep.a0 = angle; - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, m_xf, m_xf); - } - - m_world->m_contactManager.FindNewContacts(); + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, m_xf, m_xf); + } } void b2Body::SynchronizeFixtures() { - b2Transform xf1; - xf1.q.Set(m_sweep.a0); - xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); + b2Transform xf1; + xf1.q.Set(m_sweep.a0); + xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, xf1, m_xf); - } + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->Synchronize(broadPhase, xf1, m_xf); + } } void b2Body::SetActive(bool flag) { - b2Assert(m_world->IsLocked() == false); + b2Assert(m_world->IsLocked() == false); - if (flag == IsActive()) - { - return; - } + if (flag == IsActive()) + { + return; + } - if (flag) - { - m_flags |= e_activeFlag; + if (flag) + { + m_flags |= e_activeFlag; - // Create all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->CreateProxies(broadPhase, m_xf); - } + // Create all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->CreateProxies(broadPhase, m_xf); + } - // Contacts are created the next time step. - } - else - { - m_flags &= ~e_activeFlag; + // Contacts are created the next time step. + } + else + { + m_flags &= ~e_activeFlag; - // Destroy all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->DestroyProxies(broadPhase); - } + // Destroy all proxies. + b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + f->DestroyProxies(broadPhase); + } - // Destroy the attached contacts. - b2ContactEdge* ce = m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_world->m_contactManager.Destroy(ce0->contact); - } - m_contactList = NULL; - } + // Destroy the attached contacts. + b2ContactEdge* ce = m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_world->m_contactManager.Destroy(ce0->contact); + } + m_contactList = NULL; + } +} + +void b2Body::SetFixedRotation(bool flag) +{ + bool status = (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; + if (status == flag) + { + return; + } + + if (flag) + { + m_flags |= e_fixedRotationFlag; + } + else + { + m_flags &= ~e_fixedRotationFlag; + } + + m_angularVelocity = 0.0f; + + ResetMassData(); } void b2Body::Dump() { - int32 bodyIndex = m_islandIndex; + int32 bodyIndex = m_islandIndex; - b2Log("{\n"); - b2Log(" b2BodyDef bd;\n"); - b2Log(" bd.type = b2BodyType(%d);\n", m_type); - b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); - b2Log(" bd.angle = %.15lef;\n", m_sweep.a); - b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); - b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); - b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); - b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); - b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); - b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); - b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); - b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); - b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); - b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); - b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); - b2Log("\n"); - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - b2Log(" {\n"); - f->Dump(bodyIndex); - b2Log(" }\n"); - } - b2Log("}\n"); -} \ No newline at end of file + b2Log("{\n"); + b2Log(" b2BodyDef bd;\n"); + b2Log(" bd.type = b2BodyType(%d);\n", m_type); + b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); + b2Log(" bd.angle = %.15lef;\n", m_sweep.a); + b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); + b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); + b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); + b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); + b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); + b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); + b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); + b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); + b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); + b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); + b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); + b2Log("\n"); + for (b2Fixture* f = m_fixtureList; f; f = f->m_next) + { + b2Log(" {\n"); + f->Dump(bodyIndex); + b2Log(" }\n"); + } + b2Log("}\n"); +} diff --git a/external/Box2D/Dynamics/b2Body.h b/external/Box2D/Dynamics/b2Body.h index e2d16bf630..24bae64039 100644 --- a/external/Box2D/Dynamics/b2Body.h +++ b/external/Box2D/Dynamics/b2Body.h @@ -38,809 +38,823 @@ struct b2ContactEdge; /// dynamic: positive mass, non-zero velocity determined by forces, moved by solver enum b2BodyType { - b2_staticBody = 0, - b2_kinematicBody, - b2_dynamicBody + b2_staticBody = 0, + b2_kinematicBody, + b2_dynamicBody - // TODO_ERIN - //b2_bulletBody, + // TODO_ERIN + //b2_bulletBody, }; /// A body definition holds all the data needed to construct a rigid body. /// You can safely re-use body definitions. Shapes are added to a body after construction. struct b2BodyDef { - /// This constructor sets the body definition default values. - b2BodyDef() - { - userData = NULL; - position.Set(0.0f, 0.0f); - angle = 0.0f; - linearVelocity.Set(0.0f, 0.0f); - angularVelocity = 0.0f; - linearDamping = 0.0f; - angularDamping = 0.0f; - allowSleep = true; - awake = true; - fixedRotation = false; - bullet = false; - type = b2_staticBody; - active = true; - gravityScale = 1.0f; - } + /// This constructor sets the body definition default values. + b2BodyDef() + { + userData = NULL; + position.Set(0.0f, 0.0f); + angle = 0.0f; + linearVelocity.Set(0.0f, 0.0f); + angularVelocity = 0.0f; + linearDamping = 0.0f; + angularDamping = 0.0f; + allowSleep = true; + awake = true; + fixedRotation = false; + bullet = false; + type = b2_staticBody; + active = true; + gravityScale = 1.0f; + } - /// The body type: static, kinematic, or dynamic. - /// Note: if a dynamic body would have zero mass, the mass is set to one. - b2BodyType type; + /// The body type: static, kinematic, or dynamic. + /// Note: if a dynamic body would have zero mass, the mass is set to one. + b2BodyType type; - /// The world position of the body. Avoid creating bodies at the origin - /// since this can lead to many overlapping shapes. - b2Vec2 position; + /// The world position of the body. Avoid creating bodies at the origin + /// since this can lead to many overlapping shapes. + b2Vec2 position; - /// The world angle of the body in radians. - float32 angle; + /// The world angle of the body in radians. + float32 angle; - /// The linear velocity of the body's origin in world co-ordinates. - b2Vec2 linearVelocity; + /// The linear velocity of the body's origin in world co-ordinates. + b2Vec2 linearVelocity; - /// The angular velocity of the body. - float32 angularVelocity; + /// The angular velocity of the body. + float32 angularVelocity; - /// Linear damping is use to reduce the linear velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 linearDamping; + /// Linear damping is use to reduce the linear velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 linearDamping; - /// Angular damping is use to reduce the angular velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - float32 angularDamping; + /// Angular damping is use to reduce the angular velocity. The damping parameter + /// can be larger than 1.0f but the damping effect becomes sensitive to the + /// time step when the damping parameter is large. + float32 angularDamping; - /// Set this flag to false if this body should never fall asleep. Note that - /// this increases CPU usage. - bool allowSleep; + /// Set this flag to false if this body should never fall asleep. Note that + /// this increases CPU usage. + bool allowSleep; - /// Is this body initially awake or sleeping? - bool awake; + /// Is this body initially awake or sleeping? + bool awake; - /// Should this body be prevented from rotating? Useful for characters. - bool fixedRotation; + /// Should this body be prevented from rotating? Useful for characters. + bool fixedRotation; - /// Is this a fast moving body that should be prevented from tunneling through - /// other moving bodies? Note that all bodies are prevented from tunneling through - /// kinematic and static bodies. This setting is only considered on dynamic bodies. - /// @warning You should use this flag sparingly since it increases processing time. - bool bullet; + /// Is this a fast moving body that should be prevented from tunneling through + /// other moving bodies? Note that all bodies are prevented from tunneling through + /// kinematic and static bodies. This setting is only considered on dynamic bodies. + /// @warning You should use this flag sparingly since it increases processing time. + bool bullet; - /// Does this body start out active? - bool active; + /// Does this body start out active? + bool active; - /// Use this to store application specific body data. - void* userData; + /// Use this to store application specific body data. + void* userData; - /// Scale the gravity applied to this body. - float32 gravityScale; + /// Scale the gravity applied to this body. + float32 gravityScale; }; /// A rigid body. These are created via b2World::CreateBody. class b2Body { public: - /// Creates a fixture and attach it to this body. Use this function if you need - /// to set some fixture parameters, like friction. Otherwise you can create the - /// fixture directly from a shape. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// Contacts are not created until the next time step. - /// @param def the fixture definition. - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2FixtureDef* def); + /// Creates a fixture and attach it to this body. Use this function if you need + /// to set some fixture parameters, like friction. Otherwise you can create the + /// fixture directly from a shape. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// Contacts are not created until the next time step. + /// @param def the fixture definition. + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2FixtureDef* def); - /// Creates a fixture from a shape and attach it to this body. - /// This is a convenience function. Use b2FixtureDef if you need to set parameters - /// like friction, restitution, user data, or filtering. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// @param shape the shape to be cloned. - /// @param density the shape density (set to zero for static bodies). - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2Shape* shape, float32 density); + /// Creates a fixture from a shape and attach it to this body. + /// This is a convenience function. Use b2FixtureDef if you need to set parameters + /// like friction, restitution, user data, or filtering. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// @param shape the shape to be cloned. + /// @param density the shape density (set to zero for static bodies). + /// @warning This function is locked during callbacks. + b2Fixture* CreateFixture(const b2Shape* shape, float32 density); - /// Destroy a fixture. This removes the fixture from the broad-phase and - /// destroys all contacts associated with this fixture. This will - /// automatically adjust the mass of the body if the body is dynamic and the - /// fixture has positive density. - /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. - /// @param fixture the fixture to be removed. - /// @warning This function is locked during callbacks. - void DestroyFixture(b2Fixture* fixture); + /// Destroy a fixture. This removes the fixture from the broad-phase and + /// destroys all contacts associated with this fixture. This will + /// automatically adjust the mass of the body if the body is dynamic and the + /// fixture has positive density. + /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. + /// @param fixture the fixture to be removed. + /// @warning This function is locked during callbacks. + void DestroyFixture(b2Fixture* fixture); - /// Set the position of the body's origin and rotation. - /// This breaks any contacts and wakes the other bodies. - /// Manipulating a body's transform may cause non-physical behavior. - /// @param position the world position of the body's local origin. - /// @param angle the world rotation in radians. - void SetTransform(const b2Vec2& position, float32 angle); + /// Set the position of the body's origin and rotation. + /// Manipulating a body's transform may cause non-physical behavior. + /// Note: contacts are updated on the next call to b2World::Step. + /// @param position the world position of the body's local origin. + /// @param angle the world rotation in radians. + void SetTransform(const b2Vec2& position, float32 angle); - /// Get the body transform for the body's origin. - /// @return the world transform of the body's origin. - const b2Transform& GetTransform() const; + /// Get the body transform for the body's origin. + /// @return the world transform of the body's origin. + const b2Transform& GetTransform() const; - /// Get the world body origin position. - /// @return the world position of the body's origin. - const b2Vec2& GetPosition() const; + /// Get the world body origin position. + /// @return the world position of the body's origin. + const b2Vec2& GetPosition() const; - /// Get the angle in radians. - /// @return the current world rotation angle in radians. - float32 GetAngle() const; + /// Get the angle in radians. + /// @return the current world rotation angle in radians. + float32 GetAngle() const; - /// Get the world position of the center of mass. - const b2Vec2& GetWorldCenter() const; + /// Get the world position of the center of mass. + const b2Vec2& GetWorldCenter() const; - /// Get the local position of the center of mass. - const b2Vec2& GetLocalCenter() const; + /// Get the local position of the center of mass. + const b2Vec2& GetLocalCenter() const; - /// Set the linear velocity of the center of mass. - /// @param v the new linear velocity of the center of mass. - void SetLinearVelocity(const b2Vec2& v); + /// Set the linear velocity of the center of mass. + /// @param v the new linear velocity of the center of mass. + void SetLinearVelocity(const b2Vec2& v); - /// Get the linear velocity of the center of mass. - /// @return the linear velocity of the center of mass. - b2Vec2 GetLinearVelocity() const; + /// Get the linear velocity of the center of mass. + /// @return the linear velocity of the center of mass. + const b2Vec2& GetLinearVelocity() const; - /// Set the angular velocity. - /// @param omega the new angular velocity in radians/second. - void SetAngularVelocity(float32 omega); + /// Set the angular velocity. + /// @param omega the new angular velocity in radians/second. + void SetAngularVelocity(float32 omega); - /// Get the angular velocity. - /// @return the angular velocity in radians/second. - float32 GetAngularVelocity() const; + /// Get the angular velocity. + /// @return the angular velocity in radians/second. + float32 GetAngularVelocity() const; - /// Apply a force at a world point. If the force is not - /// applied at the center of mass, it will generate a torque and - /// affect the angular velocity. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param point the world position of the point of application. - void ApplyForce(const b2Vec2& force, const b2Vec2& point); + /// Apply a force at a world point. If the force is not + /// applied at the center of mass, it will generate a torque and + /// affect the angular velocity. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + /// @param point the world position of the point of application. + /// @param wake also wake up the body + void ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake); - /// Apply a force to the center of mass. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - void ApplyForceToCenter(const b2Vec2& force); + /// Apply a force to the center of mass. This wakes up the body. + /// @param force the world force vector, usually in Newtons (N). + /// @param wake also wake up the body + void ApplyForceToCenter(const b2Vec2& force, bool wake); - /// Apply a torque. This affects the angular velocity - /// without affecting the linear velocity of the center of mass. - /// This wakes up the body. - /// @param torque about the z-axis (out of the screen), usually in N-m. - void ApplyTorque(float32 torque); + /// Apply a torque. This affects the angular velocity + /// without affecting the linear velocity of the center of mass. + /// This wakes up the body. + /// @param torque about the z-axis (out of the screen), usually in N-m. + /// @param wake also wake up the body + void ApplyTorque(float32 torque, bool wake); - /// Apply an impulse at a point. This immediately modifies the velocity. - /// It also modifies the angular velocity if the point of application - /// is not at the center of mass. This wakes up the body. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param point the world position of the point of application. - void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); + /// Apply an impulse at a point. This immediately modifies the velocity. + /// It also modifies the angular velocity if the point of application + /// is not at the center of mass. This wakes up the body. + /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. + /// @param point the world position of the point of application. + /// @param wake also wake up the body + void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake); - /// Apply an angular impulse. - /// @param impulse the angular impulse in units of kg*m*m/s - void ApplyAngularImpulse(float32 impulse); + /// Apply an angular impulse. + /// @param impulse the angular impulse in units of kg*m*m/s + /// @param wake also wake up the body + void ApplyAngularImpulse(float32 impulse, bool wake); - /// Get the total mass of the body. - /// @return the mass, usually in kilograms (kg). - float32 GetMass() const; + /// Get the total mass of the body. + /// @return the mass, usually in kilograms (kg). + float32 GetMass() const; - /// Get the rotational inertia of the body about the local origin. - /// @return the rotational inertia, usually in kg-m^2. - float32 GetInertia() const; + /// Get the rotational inertia of the body about the local origin. + /// @return the rotational inertia, usually in kg-m^2. + float32 GetInertia() const; - /// Get the mass data of the body. - /// @return a struct containing the mass, inertia and center of the body. - void GetMassData(b2MassData* data) const; + /// Get the mass data of the body. + /// @return a struct containing the mass, inertia and center of the body. + void GetMassData(b2MassData* data) const; - /// Set the mass properties to override the mass properties of the fixtures. - /// Note that this changes the center of mass position. - /// Note that creating or destroying fixtures can also alter the mass. - /// This function has no effect if the body isn't dynamic. - /// @param massData the mass properties. - void SetMassData(const b2MassData* data); + /// Set the mass properties to override the mass properties of the fixtures. + /// Note that this changes the center of mass position. + /// Note that creating or destroying fixtures can also alter the mass. + /// This function has no effect if the body isn't dynamic. + /// @param massData the mass properties. + void SetMassData(const b2MassData* data); - /// This resets the mass properties to the sum of the mass properties of the fixtures. - /// This normally does not need to be called unless you called SetMassData to override - /// the mass and you later want to reset the mass. - void ResetMassData(); + /// This resets the mass properties to the sum of the mass properties of the fixtures. + /// This normally does not need to be called unless you called SetMassData to override + /// the mass and you later want to reset the mass. + void ResetMassData(); - /// Get the world coordinates of a point given the local coordinates. - /// @param localPoint a point on the body measured relative the the body's origin. - /// @return the same point expressed in world coordinates. - b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; + /// Get the world coordinates of a point given the local coordinates. + /// @param localPoint a point on the body measured relative the the body's origin. + /// @return the same point expressed in world coordinates. + b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; - /// Get the world coordinates of a vector given the local coordinates. - /// @param localVector a vector fixed in the body. - /// @return the same vector expressed in world coordinates. - b2Vec2 GetWorldVector(const b2Vec2& localVector) const; + /// Get the world coordinates of a vector given the local coordinates. + /// @param localVector a vector fixed in the body. + /// @return the same vector expressed in world coordinates. + b2Vec2 GetWorldVector(const b2Vec2& localVector) const; - /// Gets a local point relative to the body's origin given a world point. - /// @param a point in world coordinates. - /// @return the corresponding local point relative to the body's origin. - b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; + /// Gets a local point relative to the body's origin given a world point. + /// @param a point in world coordinates. + /// @return the corresponding local point relative to the body's origin. + b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; - /// Gets a local vector given a world vector. - /// @param a vector in world coordinates. - /// @return the corresponding local vector. - b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; + /// Gets a local vector given a world vector. + /// @param a vector in world coordinates. + /// @return the corresponding local vector. + b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; - /// Get the world linear velocity of a world point attached to this body. - /// @param a point in world coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; + /// Get the world linear velocity of a world point attached to this body. + /// @param a point in world coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; - /// Get the world velocity of a local point. - /// @param a point in local coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; + /// Get the world velocity of a local point. + /// @param a point in local coordinates. + /// @return the world velocity of a point. + b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; - /// Get the linear damping of the body. - float32 GetLinearDamping() const; + /// Get the linear damping of the body. + float32 GetLinearDamping() const; - /// Set the linear damping of the body. - void SetLinearDamping(float32 linearDamping); + /// Set the linear damping of the body. + void SetLinearDamping(float32 linearDamping); - /// Get the angular damping of the body. - float32 GetAngularDamping() const; + /// Get the angular damping of the body. + float32 GetAngularDamping() const; - /// Set the angular damping of the body. - void SetAngularDamping(float32 angularDamping); + /// Set the angular damping of the body. + void SetAngularDamping(float32 angularDamping); - /// Get the gravity scale of the body. - float32 GetGravityScale() const; + /// Get the gravity scale of the body. + float32 GetGravityScale() const; - /// Set the gravity scale of the body. - void SetGravityScale(float32 scale); + /// Set the gravity scale of the body. + void SetGravityScale(float32 scale); - /// Set the type of this body. This may alter the mass and velocity. - void SetType(b2BodyType type); + /// Set the type of this body. This may alter the mass and velocity. + void SetType(b2BodyType type); - /// Get the type of this body. - b2BodyType GetType() const; + /// Get the type of this body. + b2BodyType GetType() const; - /// Should this body be treated like a bullet for continuous collision detection? - void SetBullet(bool flag); + /// Should this body be treated like a bullet for continuous collision detection? + void SetBullet(bool flag); - /// Is this body treated like a bullet for continuous collision detection? - bool IsBullet() const; + /// Is this body treated like a bullet for continuous collision detection? + bool IsBullet() const; - /// You can disable sleeping on this body. If you disable sleeping, the - /// body will be woken. - void SetSleepingAllowed(bool flag); + /// You can disable sleeping on this body. If you disable sleeping, the + /// body will be woken. + void SetSleepingAllowed(bool flag); - /// Is this body allowed to sleep - bool IsSleepingAllowed() const; + /// Is this body allowed to sleep + bool IsSleepingAllowed() const; - /// Set the sleep state of the body. A sleeping body has very - /// low CPU cost. - /// @param flag set to true to put body to sleep, false to wake it. - void SetAwake(bool flag); + /// Set the sleep state of the body. A sleeping body has very + /// low CPU cost. + /// @param flag set to true to wake the body, false to put it to sleep. + void SetAwake(bool flag); - /// Get the sleeping state of this body. - /// @return true if the body is sleeping. - bool IsAwake() const; + /// Get the sleeping state of this body. + /// @return true if the body is awake. + bool IsAwake() const; - /// Set the active state of the body. An inactive body is not - /// simulated and cannot be collided with or woken up. - /// If you pass a flag of true, all fixtures will be added to the - /// broad-phase. - /// If you pass a flag of false, all fixtures will be removed from - /// the broad-phase and all contacts will be destroyed. - /// Fixtures and joints are otherwise unaffected. You may continue - /// to create/destroy fixtures and joints on inactive bodies. - /// Fixtures on an inactive body are implicitly inactive and will - /// not participate in collisions, ray-casts, or queries. - /// Joints connected to an inactive body are implicitly inactive. - /// An inactive body is still owned by a b2World object and remains - /// in the body list. - void SetActive(bool flag); + /// Set the active state of the body. An inactive body is not + /// simulated and cannot be collided with or woken up. + /// If you pass a flag of true, all fixtures will be added to the + /// broad-phase. + /// If you pass a flag of false, all fixtures will be removed from + /// the broad-phase and all contacts will be destroyed. + /// Fixtures and joints are otherwise unaffected. You may continue + /// to create/destroy fixtures and joints on inactive bodies. + /// Fixtures on an inactive body are implicitly inactive and will + /// not participate in collisions, ray-casts, or queries. + /// Joints connected to an inactive body are implicitly inactive. + /// An inactive body is still owned by a b2World object and remains + /// in the body list. + void SetActive(bool flag); - /// Get the active state of the body. - bool IsActive() const; + /// Get the active state of the body. + bool IsActive() const; - /// Set this body to have fixed rotation. This causes the mass - /// to be reset. - void SetFixedRotation(bool flag); + /// Set this body to have fixed rotation. This causes the mass + /// to be reset. + void SetFixedRotation(bool flag); - /// Does this body have fixed rotation? - bool IsFixedRotation() const; + /// Does this body have fixed rotation? + bool IsFixedRotation() const; - /// Get the list of all fixtures attached to this body. - b2Fixture* GetFixtureList(); - const b2Fixture* GetFixtureList() const; + /// Get the list of all fixtures attached to this body. + b2Fixture* GetFixtureList(); + const b2Fixture* GetFixtureList() const; - /// Get the list of all joints attached to this body. - b2JointEdge* GetJointList(); - const b2JointEdge* GetJointList() const; + /// Get the list of all joints attached to this body. + b2JointEdge* GetJointList(); + const b2JointEdge* GetJointList() const; - /// Get the list of all contacts attached to this body. - /// @warning this list changes during the time step and you may - /// miss some collisions if you don't use b2ContactListener. - b2ContactEdge* GetContactList(); - const b2ContactEdge* GetContactList() const; + /// Get the list of all contacts attached to this body. + /// @warning this list changes during the time step and you may + /// miss some collisions if you don't use b2ContactListener. + b2ContactEdge* GetContactList(); + const b2ContactEdge* GetContactList() const; - /// Get the next body in the world's body list. - b2Body* GetNext(); - const b2Body* GetNext() const; + /// Get the next body in the world's body list. + b2Body* GetNext(); + const b2Body* GetNext() const; - /// Get the user data pointer that was provided in the body definition. - void* GetUserData() const; + /// Get the user data pointer that was provided in the body definition. + void* GetUserData() const; - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); - /// Get the parent world of this body. - b2World* GetWorld(); - const b2World* GetWorld() const; + /// Get the parent world of this body. + b2World* GetWorld(); + const b2World* GetWorld() const; - /// Dump this body to a log file - void Dump(); + /// Dump this body to a log file + void Dump(); private: - friend class b2World; - friend class b2Island; - friend class b2ContactManager; - friend class b2ContactSolver; - friend class b2Contact; - - friend class b2DistanceJoint; - friend class b2GearJoint; - friend class b2WheelJoint; - friend class b2MouseJoint; - friend class b2PrismaticJoint; - friend class b2PulleyJoint; - friend class b2RevoluteJoint; - friend class b2WeldJoint; - friend class b2FrictionJoint; - friend class b2RopeJoint; + friend class b2World; + friend class b2Island; + friend class b2ContactManager; + friend class b2ContactSolver; + friend class b2Contact; + + friend class b2DistanceJoint; + friend class b2FrictionJoint; + friend class b2GearJoint; + friend class b2MotorJoint; + friend class b2MouseJoint; + friend class b2PrismaticJoint; + friend class b2PulleyJoint; + friend class b2RevoluteJoint; + friend class b2RopeJoint; + friend class b2WeldJoint; + friend class b2WheelJoint; - // m_flags - enum - { - e_islandFlag = 0x0001, - e_awakeFlag = 0x0002, - e_autoSleepFlag = 0x0004, - e_bulletFlag = 0x0008, - e_fixedRotationFlag = 0x0010, - e_activeFlag = 0x0020, - e_toiFlag = 0x0040 - }; + // m_flags + enum + { + e_islandFlag = 0x0001, + e_awakeFlag = 0x0002, + e_autoSleepFlag = 0x0004, + e_bulletFlag = 0x0008, + e_fixedRotationFlag = 0x0010, + e_activeFlag = 0x0020, + e_toiFlag = 0x0040 + }; - b2Body(const b2BodyDef* bd, b2World* world); - ~b2Body(); + b2Body(const b2BodyDef* bd, b2World* world); + ~b2Body(); - void SynchronizeFixtures(); - void SynchronizeTransform(); + void SynchronizeFixtures(); + void SynchronizeTransform(); - // This is used to prevent connected bodies from colliding. - // It may lie, depending on the collideConnected flag. - bool ShouldCollide(const b2Body* other) const; + // This is used to prevent connected bodies from colliding. + // It may lie, depending on the collideConnected flag. + bool ShouldCollide(const b2Body* other) const; - void Advance(float32 t); + void Advance(float32 t); - b2BodyType m_type; + b2BodyType m_type; - uint16 m_flags; + uint16 m_flags; - int32 m_islandIndex; + int32 m_islandIndex; - b2Transform m_xf; // the body origin transform - b2Sweep m_sweep; // the swept motion for CCD + b2Transform m_xf; // the body origin transform + b2Sweep m_sweep; // the swept motion for CCD - b2Vec2 m_linearVelocity; - float32 m_angularVelocity; + b2Vec2 m_linearVelocity; + float32 m_angularVelocity; - b2Vec2 m_force; - float32 m_torque; + b2Vec2 m_force; + float32 m_torque; - b2World* m_world; - b2Body* m_prev; - b2Body* m_next; + b2World* m_world; + b2Body* m_prev; + b2Body* m_next; - b2Fixture* m_fixtureList; - int32 m_fixtureCount; + b2Fixture* m_fixtureList; + int32 m_fixtureCount; - b2JointEdge* m_jointList; - b2ContactEdge* m_contactList; + b2JointEdge* m_jointList; + b2ContactEdge* m_contactList; - float32 m_mass, m_invMass; + float32 m_mass, m_invMass; - // Rotational inertia about the center of mass. - float32 m_I, m_invI; + // Rotational inertia about the center of mass. + float32 m_I, m_invI; - float32 m_linearDamping; - float32 m_angularDamping; - float32 m_gravityScale; + float32 m_linearDamping; + float32 m_angularDamping; + float32 m_gravityScale; - float32 m_sleepTime; + float32 m_sleepTime; - void* m_userData; + void* m_userData; }; inline b2BodyType b2Body::GetType() const { - return m_type; + return m_type; } inline const b2Transform& b2Body::GetTransform() const { - return m_xf; + return m_xf; } inline const b2Vec2& b2Body::GetPosition() const { - return m_xf.p; + return m_xf.p; } inline float32 b2Body::GetAngle() const { - return m_sweep.a; + return m_sweep.a; } inline const b2Vec2& b2Body::GetWorldCenter() const { - return m_sweep.c; + return m_sweep.c; } inline const b2Vec2& b2Body::GetLocalCenter() const { - return m_sweep.localCenter; + return m_sweep.localCenter; } inline void b2Body::SetLinearVelocity(const b2Vec2& v) { - if (m_type == b2_staticBody) - { - return; - } + if (m_type == b2_staticBody) + { + return; + } - if (b2Dot(v,v) > 0.0f) - { - SetAwake(true); - } + if (b2Dot(v,v) > 0.0f) + { + SetAwake(true); + } - m_linearVelocity = v; + m_linearVelocity = v; } -inline b2Vec2 b2Body::GetLinearVelocity() const +inline const b2Vec2& b2Body::GetLinearVelocity() const { - return m_linearVelocity; + return m_linearVelocity; } inline void b2Body::SetAngularVelocity(float32 w) { - if (m_type == b2_staticBody) - { - return; - } + if (m_type == b2_staticBody) + { + return; + } - if (w * w > 0.0f) - { - SetAwake(true); - } + if (w * w > 0.0f) + { + SetAwake(true); + } - m_angularVelocity = w; + m_angularVelocity = w; } inline float32 b2Body::GetAngularVelocity() const { - return m_angularVelocity; + return m_angularVelocity; } inline float32 b2Body::GetMass() const { - return m_mass; + return m_mass; } inline float32 b2Body::GetInertia() const { - return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); + return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); } inline void b2Body::GetMassData(b2MassData* data) const { - data->mass = m_mass; - data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); - data->center = m_sweep.localCenter; + data->mass = m_mass; + data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); + data->center = m_sweep.localCenter; } inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const { - return b2Mul(m_xf, localPoint); + return b2Mul(m_xf, localPoint); } inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const { - return b2Mul(m_xf.q, localVector); + return b2Mul(m_xf.q, localVector); } inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const { - return b2MulT(m_xf, worldPoint); + return b2MulT(m_xf, worldPoint); } inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const { - return b2MulT(m_xf.q, worldVector); + return b2MulT(m_xf.q, worldVector); } inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const { - return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); + return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); } inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const { - return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); + return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); } inline float32 b2Body::GetLinearDamping() const { - return m_linearDamping; + return m_linearDamping; } inline void b2Body::SetLinearDamping(float32 linearDamping) { - m_linearDamping = linearDamping; + m_linearDamping = linearDamping; } inline float32 b2Body::GetAngularDamping() const { - return m_angularDamping; + return m_angularDamping; } inline void b2Body::SetAngularDamping(float32 angularDamping) { - m_angularDamping = angularDamping; + m_angularDamping = angularDamping; } inline float32 b2Body::GetGravityScale() const { - return m_gravityScale; + return m_gravityScale; } inline void b2Body::SetGravityScale(float32 scale) { - m_gravityScale = scale; + m_gravityScale = scale; } inline void b2Body::SetBullet(bool flag) { - if (flag) - { - m_flags |= e_bulletFlag; - } - else - { - m_flags &= ~e_bulletFlag; - } + if (flag) + { + m_flags |= e_bulletFlag; + } + else + { + m_flags &= ~e_bulletFlag; + } } inline bool b2Body::IsBullet() const { - return (m_flags & e_bulletFlag) == e_bulletFlag; + return (m_flags & e_bulletFlag) == e_bulletFlag; } inline void b2Body::SetAwake(bool flag) { - if (flag) - { - if ((m_flags & e_awakeFlag) == 0) - { - m_flags |= e_awakeFlag; - m_sleepTime = 0.0f; - } - } - else - { - m_flags &= ~e_awakeFlag; - m_sleepTime = 0.0f; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_force.SetZero(); - m_torque = 0.0f; - } + if (flag) + { + if ((m_flags & e_awakeFlag) == 0) + { + m_flags |= e_awakeFlag; + m_sleepTime = 0.0f; + } + } + else + { + m_flags &= ~e_awakeFlag; + m_sleepTime = 0.0f; + m_linearVelocity.SetZero(); + m_angularVelocity = 0.0f; + m_force.SetZero(); + m_torque = 0.0f; + } } inline bool b2Body::IsAwake() const { - return (m_flags & e_awakeFlag) == e_awakeFlag; + return (m_flags & e_awakeFlag) == e_awakeFlag; } inline bool b2Body::IsActive() const { - return (m_flags & e_activeFlag) == e_activeFlag; -} - -inline void b2Body::SetFixedRotation(bool flag) -{ - if (flag) - { - m_flags |= e_fixedRotationFlag; - } - else - { - m_flags &= ~e_fixedRotationFlag; - } - - ResetMassData(); + return (m_flags & e_activeFlag) == e_activeFlag; } inline bool b2Body::IsFixedRotation() const { - return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; + return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; } inline void b2Body::SetSleepingAllowed(bool flag) { - if (flag) - { - m_flags |= e_autoSleepFlag; - } - else - { - m_flags &= ~e_autoSleepFlag; - SetAwake(true); - } + if (flag) + { + m_flags |= e_autoSleepFlag; + } + else + { + m_flags &= ~e_autoSleepFlag; + SetAwake(true); + } } inline bool b2Body::IsSleepingAllowed() const { - return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; + return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; } inline b2Fixture* b2Body::GetFixtureList() { - return m_fixtureList; + return m_fixtureList; } inline const b2Fixture* b2Body::GetFixtureList() const { - return m_fixtureList; + return m_fixtureList; } inline b2JointEdge* b2Body::GetJointList() { - return m_jointList; + return m_jointList; } inline const b2JointEdge* b2Body::GetJointList() const { - return m_jointList; + return m_jointList; } inline b2ContactEdge* b2Body::GetContactList() { - return m_contactList; + return m_contactList; } inline const b2ContactEdge* b2Body::GetContactList() const { - return m_contactList; + return m_contactList; } inline b2Body* b2Body::GetNext() { - return m_next; + return m_next; } inline const b2Body* b2Body::GetNext() const { - return m_next; + return m_next; } inline void b2Body::SetUserData(void* data) { - m_userData = data; + m_userData = data; } inline void* b2Body::GetUserData() const { - return m_userData; + return m_userData; } -inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) +inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake) { - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - if (IsAwake() == false) - { - SetAwake(true); - } + if (wake && (m_flags & e_awakeFlag) == 0) + { + SetAwake(true); + } - m_force += force; - m_torque += b2Cross(point - m_sweep.c, force); + // Don't accumulate a force if the body is sleeping. + if (m_flags & e_awakeFlag) + { + m_force += force; + m_torque += b2Cross(point - m_sweep.c, force); + } } -inline void b2Body::ApplyForceToCenter(const b2Vec2& force) +inline void b2Body::ApplyForceToCenter(const b2Vec2& force, bool wake) { - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - if (IsAwake() == false) - { - SetAwake(true); - } + if (wake && (m_flags & e_awakeFlag) == 0) + { + SetAwake(true); + } - m_force += force; + // Don't accumulate a force if the body is sleeping + if (m_flags & e_awakeFlag) + { + m_force += force; + } } -inline void b2Body::ApplyTorque(float32 torque) +inline void b2Body::ApplyTorque(float32 torque, bool wake) { - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - if (IsAwake() == false) - { - SetAwake(true); - } + if (wake && (m_flags & e_awakeFlag) == 0) + { + SetAwake(true); + } - m_torque += torque; + // Don't accumulate a force if the body is sleeping + if (m_flags & e_awakeFlag) + { + m_torque += torque; + } } -inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) +inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake) { - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - if (IsAwake() == false) - { - SetAwake(true); - } - m_linearVelocity += m_invMass * impulse; - m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); + if (wake && (m_flags & e_awakeFlag) == 0) + { + SetAwake(true); + } + + // Don't accumulate velocity if the body is sleeping + if (m_flags & e_awakeFlag) + { + m_linearVelocity += m_invMass * impulse; + m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); + } } -inline void b2Body::ApplyAngularImpulse(float32 impulse) +inline void b2Body::ApplyAngularImpulse(float32 impulse, bool wake) { - if (m_type != b2_dynamicBody) - { - return; - } + if (m_type != b2_dynamicBody) + { + return; + } - if (IsAwake() == false) - { - SetAwake(true); - } - m_angularVelocity += m_invI * impulse; + if (wake && (m_flags & e_awakeFlag) == 0) + { + SetAwake(true); + } + + // Don't accumulate velocity if the body is sleeping + if (m_flags & e_awakeFlag) + { + m_angularVelocity += m_invI * impulse; + } } inline void b2Body::SynchronizeTransform() { - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); } inline void b2Body::Advance(float32 alpha) { - // Advance to the new safe time. This doesn't sync the broad-phase. - m_sweep.Advance(alpha); - m_sweep.c = m_sweep.c0; - m_sweep.a = m_sweep.a0; - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); + // Advance to the new safe time. This doesn't sync the broad-phase. + m_sweep.Advance(alpha); + m_sweep.c = m_sweep.c0; + m_sweep.a = m_sweep.a0; + m_xf.q.Set(m_sweep.a); + m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); } inline b2World* b2Body::GetWorld() { - return m_world; + return m_world; } inline const b2World* b2Body::GetWorld() const { - return m_world; + return m_world; } #endif diff --git a/external/Box2D/Dynamics/b2ContactManager.cpp b/external/Box2D/Dynamics/b2ContactManager.cpp index c14cc4ce45..d8a189b74e 100644 --- a/external/Box2D/Dynamics/b2ContactManager.cpp +++ b/external/Box2D/Dynamics/b2ContactManager.cpp @@ -27,76 +27,76 @@ b2ContactListener b2_defaultListener; b2ContactManager::b2ContactManager() { - m_contactList = NULL; - m_contactCount = 0; - m_contactFilter = &b2_defaultFilter; - m_contactListener = &b2_defaultListener; - m_allocator = NULL; + m_contactList = NULL; + m_contactCount = 0; + m_contactFilter = &b2_defaultFilter; + m_contactListener = &b2_defaultListener; + m_allocator = NULL; } void b2ContactManager::Destroy(b2Contact* c) { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); - if (m_contactListener && c->IsTouching()) - { - m_contactListener->EndContact(c); - } + if (m_contactListener && c->IsTouching()) + { + m_contactListener->EndContact(c); + } - // Remove from the world. - if (c->m_prev) - { - c->m_prev->m_next = c->m_next; - } + // Remove from the world. + if (c->m_prev) + { + c->m_prev->m_next = c->m_next; + } - if (c->m_next) - { - c->m_next->m_prev = c->m_prev; - } + if (c->m_next) + { + c->m_next->m_prev = c->m_prev; + } - if (c == m_contactList) - { - m_contactList = c->m_next; - } + if (c == m_contactList) + { + m_contactList = c->m_next; + } - // Remove from body 1 - if (c->m_nodeA.prev) - { - c->m_nodeA.prev->next = c->m_nodeA.next; - } + // Remove from body 1 + if (c->m_nodeA.prev) + { + c->m_nodeA.prev->next = c->m_nodeA.next; + } - if (c->m_nodeA.next) - { - c->m_nodeA.next->prev = c->m_nodeA.prev; - } + if (c->m_nodeA.next) + { + c->m_nodeA.next->prev = c->m_nodeA.prev; + } - if (&c->m_nodeA == bodyA->m_contactList) - { - bodyA->m_contactList = c->m_nodeA.next; - } + if (&c->m_nodeA == bodyA->m_contactList) + { + bodyA->m_contactList = c->m_nodeA.next; + } - // Remove from body 2 - if (c->m_nodeB.prev) - { - c->m_nodeB.prev->next = c->m_nodeB.next; - } + // Remove from body 2 + if (c->m_nodeB.prev) + { + c->m_nodeB.prev->next = c->m_nodeB.next; + } - if (c->m_nodeB.next) - { - c->m_nodeB.next->prev = c->m_nodeB.prev; - } + if (c->m_nodeB.next) + { + c->m_nodeB.next->prev = c->m_nodeB.prev; + } - if (&c->m_nodeB == bodyB->m_contactList) - { - bodyB->m_contactList = c->m_nodeB.next; - } + if (&c->m_nodeB == bodyB->m_contactList) + { + bodyB->m_contactList = c->m_nodeB.next; + } - // Call the factory. - b2Contact::Destroy(c, m_allocator); - --m_contactCount; + // Call the factory. + b2Contact::Destroy(c, m_allocator); + --m_contactCount; } // This is the top level collision call for the time step. Here @@ -104,190 +104,193 @@ void b2ContactManager::Destroy(b2Contact* c) // contact list. void b2ContactManager::Collide() { - // Update awake contacts. - b2Contact* c = m_contactList; - while (c) - { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Is this contact flagged for filtering? - if (c->m_flags & b2Contact::e_filterFlag) - { - // Should these bodies collide? - if (bodyB->ShouldCollide(bodyA) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } + // Update awake contacts. + b2Contact* c = m_contactList; + while (c) + { + b2Fixture* fixtureA = c->GetFixtureA(); + b2Fixture* fixtureB = c->GetFixtureB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); + + // Is this contact flagged for filtering? + if (c->m_flags & b2Contact::e_filterFlag) + { + // Should these bodies collide? + if (bodyB->ShouldCollide(bodyA) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } - // Clear the filtering flag. - c->m_flags &= ~b2Contact::e_filterFlag; - } + // Clear the filtering flag. + c->m_flags &= ~b2Contact::e_filterFlag; + } - bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; - bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; + bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; + bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - // At least one body must be awake and it must be dynamic or kinematic. - if (activeA == false && activeB == false) - { - c = c->GetNext(); - continue; - } + // At least one body must be awake and it must be dynamic or kinematic. + if (activeA == false && activeB == false) + { + c = c->GetNext(); + continue; + } - int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; - int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; - bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); + int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; + int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; + bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); - // Here we destroy contacts that cease to overlap in the broad-phase. - if (overlap == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } + // Here we destroy contacts that cease to overlap in the broad-phase. + if (overlap == false) + { + b2Contact* cNuke = c; + c = cNuke->GetNext(); + Destroy(cNuke); + continue; + } - // The contact persists. - c->Update(m_contactListener); - c = c->GetNext(); - } + // The contact persists. + c->Update(m_contactListener); + c = c->GetNext(); + } } void b2ContactManager::FindNewContacts() { - m_broadPhase.UpdatePairs(this); + m_broadPhase.UpdatePairs(this); } void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) { - b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; - b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; + b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; + b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; - b2Fixture* fixtureA = proxyA->fixture; - b2Fixture* fixtureB = proxyB->fixture; + b2Fixture* fixtureA = proxyA->fixture; + b2Fixture* fixtureB = proxyB->fixture; - int32 indexA = proxyA->childIndex; - int32 indexB = proxyB->childIndex; + int32 indexA = proxyA->childIndex; + int32 indexB = proxyB->childIndex; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); + b2Body* bodyA = fixtureA->GetBody(); + b2Body* bodyB = fixtureB->GetBody(); - // Are the fixtures on the same body? - if (bodyA == bodyB) - { - return; - } + // Are the fixtures on the same body? + if (bodyA == bodyB) + { + return; + } - // TODO_ERIN use a hash table to remove a potential bottleneck when both - // bodies have a lot of contacts. - // Does a contact already exist? - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - b2Fixture* fA = edge->contact->GetFixtureA(); - b2Fixture* fB = edge->contact->GetFixtureB(); - int32 iA = edge->contact->GetChildIndexA(); - int32 iB = edge->contact->GetChildIndexB(); + // TODO_ERIN use a hash table to remove a potential bottleneck when both + // bodies have a lot of contacts. + // Does a contact already exist? + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + b2Fixture* fA = edge->contact->GetFixtureA(); + b2Fixture* fB = edge->contact->GetFixtureB(); + int32 iA = edge->contact->GetChildIndexA(); + int32 iB = edge->contact->GetChildIndexB(); - if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) - { - // A contact already exists. - return; - } + if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) + { + // A contact already exists. + return; + } - if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) - { - // A contact already exists. - return; - } - } + if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) + { + // A contact already exists. + return; + } + } - edge = edge->next; - } + edge = edge->next; + } - // Does a joint override collision? Is at least one body dynamic? - if (bodyB->ShouldCollide(bodyA) == false) - { - return; - } + // Does a joint override collision? Is at least one body dynamic? + if (bodyB->ShouldCollide(bodyA) == false) + { + return; + } - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - return; - } + // Check user filtering. + if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) + { + return; + } - // Call the factory. - b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); - if (c == NULL) - { - return; - } + // Call the factory. + b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); + if (c == NULL) + { + return; + } - // Contact creation may swap fixtures. - fixtureA = c->GetFixtureA(); - fixtureB = c->GetFixtureB(); - indexA = c->GetChildIndexA(); - indexB = c->GetChildIndexB(); - bodyA = fixtureA->GetBody(); - bodyB = fixtureB->GetBody(); + // Contact creation may swap fixtures. + fixtureA = c->GetFixtureA(); + fixtureB = c->GetFixtureB(); + indexA = c->GetChildIndexA(); + indexB = c->GetChildIndexB(); + bodyA = fixtureA->GetBody(); + bodyB = fixtureB->GetBody(); - // Insert into the world. - c->m_prev = NULL; - c->m_next = m_contactList; - if (m_contactList != NULL) - { - m_contactList->m_prev = c; - } - m_contactList = c; + // Insert into the world. + c->m_prev = NULL; + c->m_next = m_contactList; + if (m_contactList != NULL) + { + m_contactList->m_prev = c; + } + m_contactList = c; - // Connect to island graph. + // Connect to island graph. - // Connect to body A - c->m_nodeA.contact = c; - c->m_nodeA.other = bodyB; + // Connect to body A + c->m_nodeA.contact = c; + c->m_nodeA.other = bodyB; - c->m_nodeA.prev = NULL; - c->m_nodeA.next = bodyA->m_contactList; - if (bodyA->m_contactList != NULL) - { - bodyA->m_contactList->prev = &c->m_nodeA; - } - bodyA->m_contactList = &c->m_nodeA; + c->m_nodeA.prev = NULL; + c->m_nodeA.next = bodyA->m_contactList; + if (bodyA->m_contactList != NULL) + { + bodyA->m_contactList->prev = &c->m_nodeA; + } + bodyA->m_contactList = &c->m_nodeA; - // Connect to body B - c->m_nodeB.contact = c; - c->m_nodeB.other = bodyA; + // Connect to body B + c->m_nodeB.contact = c; + c->m_nodeB.other = bodyA; - c->m_nodeB.prev = NULL; - c->m_nodeB.next = bodyB->m_contactList; - if (bodyB->m_contactList != NULL) - { - bodyB->m_contactList->prev = &c->m_nodeB; - } - bodyB->m_contactList = &c->m_nodeB; + c->m_nodeB.prev = NULL; + c->m_nodeB.next = bodyB->m_contactList; + if (bodyB->m_contactList != NULL) + { + bodyB->m_contactList->prev = &c->m_nodeB; + } + bodyB->m_contactList = &c->m_nodeB; - // Wake up the bodies - bodyA->SetAwake(true); - bodyB->SetAwake(true); + // Wake up the bodies + if (fixtureA->IsSensor() == false && fixtureB->IsSensor() == false) + { + bodyA->SetAwake(true); + bodyB->SetAwake(true); + } - ++m_contactCount; + ++m_contactCount; } diff --git a/external/Box2D/Dynamics/b2ContactManager.h b/external/Box2D/Dynamics/b2ContactManager.h index 9cb5718145..6a1d072af0 100644 --- a/external/Box2D/Dynamics/b2ContactManager.h +++ b/external/Box2D/Dynamics/b2ContactManager.h @@ -30,23 +30,23 @@ class b2BlockAllocator; class b2ContactManager { public: - b2ContactManager(); + b2ContactManager(); - // Broad-phase callback. - void AddPair(void* proxyUserDataA, void* proxyUserDataB); + // Broad-phase callback. + void AddPair(void* proxyUserDataA, void* proxyUserDataB); - void FindNewContacts(); + void FindNewContacts(); - void Destroy(b2Contact* c); + void Destroy(b2Contact* c); - void Collide(); + void Collide(); - b2BroadPhase m_broadPhase; - b2Contact* m_contactList; - int32 m_contactCount; - b2ContactFilter* m_contactFilter; - b2ContactListener* m_contactListener; - b2BlockAllocator* m_allocator; + b2BroadPhase m_broadPhase; + b2Contact* m_contactList; + int32 m_contactCount; + b2ContactFilter* m_contactFilter; + b2ContactListener* m_contactListener; + b2BlockAllocator* m_allocator; }; #endif diff --git a/external/Box2D/Dynamics/b2Fixture.cpp b/external/Box2D/Dynamics/b2Fixture.cpp index 774a78e5bb..fb17f0a3e2 100644 --- a/external/Box2D/Dynamics/b2Fixture.cpp +++ b/external/Box2D/Dynamics/b2Fixture.cpp @@ -29,275 +29,275 @@ b2Fixture::b2Fixture() { - m_userData = NULL; - m_body = NULL; - m_next = NULL; - m_proxies = NULL; - m_proxyCount = 0; - m_shape = NULL; - m_density = 0.0f; + m_userData = NULL; + m_body = NULL; + m_next = NULL; + m_proxies = NULL; + m_proxyCount = 0; + m_shape = NULL; + m_density = 0.0f; } void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) { - m_userData = def->userData; - m_friction = def->friction; - m_restitution = def->restitution; + m_userData = def->userData; + m_friction = def->friction; + m_restitution = def->restitution; - m_body = body; - m_next = NULL; + m_body = body; + m_next = NULL; - m_filter = def->filter; + m_filter = def->filter; - m_isSensor = def->isSensor; + m_isSensor = def->isSensor; - m_shape = def->shape->Clone(allocator); + m_shape = def->shape->Clone(allocator); - // Reserve proxy space - int32 childCount = m_shape->GetChildCount(); - m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); - for (int32 i = 0; i < childCount; ++i) - { - m_proxies[i].fixture = NULL; - m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; - } - m_proxyCount = 0; + // Reserve proxy space + int32 childCount = m_shape->GetChildCount(); + m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); + for (int32 i = 0; i < childCount; ++i) + { + m_proxies[i].fixture = NULL; + m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; + } + m_proxyCount = 0; - m_density = def->density; + m_density = def->density; } void b2Fixture::Destroy(b2BlockAllocator* allocator) { - // The proxies must be destroyed before calling this. - b2Assert(m_proxyCount == 0); + // The proxies must be destroyed before calling this. + b2Assert(m_proxyCount == 0); - // Free the proxy array. - int32 childCount = m_shape->GetChildCount(); - allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); - m_proxies = NULL; + // Free the proxy array. + int32 childCount = m_shape->GetChildCount(); + allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); + m_proxies = NULL; - // Free the child shape. - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - s->~b2CircleShape(); - allocator->Free(s, sizeof(b2CircleShape)); - } - break; + // Free the child shape. + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + s->~b2CircleShape(); + allocator->Free(s, sizeof(b2CircleShape)); + } + break; - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - s->~b2EdgeShape(); - allocator->Free(s, sizeof(b2EdgeShape)); - } - break; + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + s->~b2EdgeShape(); + allocator->Free(s, sizeof(b2EdgeShape)); + } + break; - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - s->~b2PolygonShape(); - allocator->Free(s, sizeof(b2PolygonShape)); - } - break; + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + s->~b2PolygonShape(); + allocator->Free(s, sizeof(b2PolygonShape)); + } + break; - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - s->~b2ChainShape(); - allocator->Free(s, sizeof(b2ChainShape)); - } - break; + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + s->~b2ChainShape(); + allocator->Free(s, sizeof(b2ChainShape)); + } + break; - default: - b2Assert(false); - break; - } + default: + b2Assert(false); + break; + } - m_shape = NULL; + m_shape = NULL; } void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) { - b2Assert(m_proxyCount == 0); + b2Assert(m_proxyCount == 0); - // Create proxies in the broad-phase. - m_proxyCount = m_shape->GetChildCount(); + // Create proxies in the broad-phase. + m_proxyCount = m_shape->GetChildCount(); - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - m_shape->ComputeAABB(&proxy->aabb, xf, i); - proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); - proxy->fixture = this; - proxy->childIndex = i; - } + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + m_shape->ComputeAABB(&proxy->aabb, xf, i); + proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); + proxy->fixture = this; + proxy->childIndex = i; + } } void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) { - // Destroy proxies in the broad-phase. - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - broadPhase->DestroyProxy(proxy->proxyId); - proxy->proxyId = b2BroadPhase::e_nullProxy; - } + // Destroy proxies in the broad-phase. + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; + broadPhase->DestroyProxy(proxy->proxyId); + proxy->proxyId = b2BroadPhase::e_nullProxy; + } - m_proxyCount = 0; + m_proxyCount = 0; } void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) { - if (m_proxyCount == 0) - { - return; - } + if (m_proxyCount == 0) + { + return; + } - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; + for (int32 i = 0; i < m_proxyCount; ++i) + { + b2FixtureProxy* proxy = m_proxies + i; - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb1, aabb2; - m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); - m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); - - proxy->aabb.Combine(aabb1, aabb2); + // Compute an AABB that covers the swept shape (may miss some rotation effect). + b2AABB aabb1, aabb2; + m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); + m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); + + proxy->aabb.Combine(aabb1, aabb2); - b2Vec2 displacement = transform2.p - transform1.p; + b2Vec2 displacement = transform2.p - transform1.p; - broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); - } + broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); + } } void b2Fixture::SetFilterData(const b2Filter& filter) { - m_filter = filter; + m_filter = filter; - Refilter(); + Refilter(); } void b2Fixture::Refilter() { - if (m_body == NULL) - { - return; - } + if (m_body == NULL) + { + return; + } - // Flag associated contacts for filtering. - b2ContactEdge* edge = m_body->GetContactList(); - while (edge) - { - b2Contact* contact = edge->contact; - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == this || fixtureB == this) - { - contact->FlagForFiltering(); - } + // Flag associated contacts for filtering. + b2ContactEdge* edge = m_body->GetContactList(); + while (edge) + { + b2Contact* contact = edge->contact; + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + if (fixtureA == this || fixtureB == this) + { + contact->FlagForFiltering(); + } - edge = edge->next; - } + edge = edge->next; + } - b2World* world = m_body->GetWorld(); + b2World* world = m_body->GetWorld(); - if (world == NULL) - { - return; - } + if (world == NULL) + { + return; + } - // Touch each proxy so that new pairs may be created - b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; - for (int32 i = 0; i < m_proxyCount; ++i) - { - broadPhase->TouchProxy(m_proxies[i].proxyId); - } + // Touch each proxy so that new pairs may be created + b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; + for (int32 i = 0; i < m_proxyCount; ++i) + { + broadPhase->TouchProxy(m_proxies[i].proxyId); + } } void b2Fixture::SetSensor(bool sensor) { - if (sensor != m_isSensor) - { - m_body->SetAwake(true); - m_isSensor = sensor; - } + if (sensor != m_isSensor) + { + m_body->SetAwake(true); + m_isSensor = sensor; + } } void b2Fixture::Dump(int32 bodyIndex) { - b2Log(" b2FixtureDef fd;\n"); - b2Log(" fd.friction = %.15lef;\n", m_friction); - b2Log(" fd.restitution = %.15lef;\n", m_restitution); - b2Log(" fd.density = %.15lef;\n", m_density); - b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); - b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); - b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); - b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); + b2Log(" b2FixtureDef fd;\n"); + b2Log(" fd.friction = %.15lef;\n", m_friction); + b2Log(" fd.restitution = %.15lef;\n", m_restitution); + b2Log(" fd.density = %.15lef;\n", m_density); + b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); + b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); + b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); + b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - b2Log(" b2CircleShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); - } - break; + switch (m_shape->m_type) + { + case b2Shape::e_circle: + { + b2CircleShape* s = (b2CircleShape*)m_shape; + b2Log(" b2CircleShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); + } + break; - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - b2Log(" b2EdgeShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); - b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); - b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); - b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); - b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); - b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); - } - break; + case b2Shape::e_edge: + { + b2EdgeShape* s = (b2EdgeShape*)m_shape; + b2Log(" b2EdgeShape shape;\n"); + b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); + b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); + b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); + b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); + b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); + b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); + b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); + } + break; - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - b2Log(" b2PolygonShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); - for (int32 i = 0; i < s->m_vertexCount; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount); - } - break; + case b2Shape::e_polygon: + { + b2PolygonShape* s = (b2PolygonShape*)m_shape; + b2Log(" b2PolygonShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); + for (int32 i = 0; i < s->m_count; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.Set(vs, %d);\n", s->m_count); + } + break; - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - b2Log(" b2ChainShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", s->m_count); - for (int32 i = 0; i < s->m_count; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); - b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); - b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); - b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); - b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); - } - break; + case b2Shape::e_chain: + { + b2ChainShape* s = (b2ChainShape*)m_shape; + b2Log(" b2ChainShape shape;\n"); + b2Log(" b2Vec2 vs[%d];\n", s->m_count); + for (int32 i = 0; i < s->m_count; ++i) + { + b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); + } + b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); + b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); + b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); + b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); + b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); + } + break; - default: - return; - } + default: + return; + } - b2Log("\n"); - b2Log(" fd.shape = &shape;\n"); - b2Log("\n"); - b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); + b2Log("\n"); + b2Log(" fd.shape = &shape;\n"); + b2Log("\n"); + b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); } diff --git a/external/Box2D/Dynamics/b2Fixture.h b/external/Box2D/Dynamics/b2Fixture.h index d390410b93..753127fbc5 100644 --- a/external/Box2D/Dynamics/b2Fixture.h +++ b/external/Box2D/Dynamics/b2Fixture.h @@ -31,72 +31,72 @@ class b2Fixture; /// This holds contact filtering data. struct b2Filter { - b2Filter() - { - categoryBits = 0x0001; - maskBits = 0xFFFF; - groupIndex = 0; - } + b2Filter() + { + categoryBits = 0x0001; + maskBits = 0xFFFF; + groupIndex = 0; + } - /// The collision category bits. Normally you would just set one bit. - uint16 categoryBits; + /// The collision category bits. Normally you would just set one bit. + uint16 categoryBits; - /// The collision mask bits. This states the categories that this - /// shape would accept for collision. - uint16 maskBits; + /// The collision mask bits. This states the categories that this + /// shape would accept for collision. + uint16 maskBits; - /// Collision groups allow a certain group of objects to never collide (negative) - /// or always collide (positive). Zero means no collision group. Non-zero group - /// filtering always wins against the mask bits. - int16 groupIndex; + /// Collision groups allow a certain group of objects to never collide (negative) + /// or always collide (positive). Zero means no collision group. Non-zero group + /// filtering always wins against the mask bits. + int16 groupIndex; }; /// A fixture definition is used to create a fixture. This class defines an /// abstract fixture definition. You can reuse fixture definitions safely. struct b2FixtureDef { - /// The constructor sets the default fixture definition values. - b2FixtureDef() - { - shape = NULL; - userData = NULL; - friction = 0.2f; - restitution = 0.0f; - density = 0.0f; - isSensor = false; - } + /// The constructor sets the default fixture definition values. + b2FixtureDef() + { + shape = NULL; + userData = NULL; + friction = 0.2f; + restitution = 0.0f; + density = 0.0f; + isSensor = false; + } - /// The shape, this must be set. The shape will be cloned, so you - /// can create the shape on the stack. - const b2Shape* shape; + /// The shape, this must be set. The shape will be cloned, so you + /// can create the shape on the stack. + const b2Shape* shape; - /// Use this to store application specific fixture data. - void* userData; + /// Use this to store application specific fixture data. + void* userData; - /// The friction coefficient, usually in the range [0,1]. - float32 friction; + /// The friction coefficient, usually in the range [0,1]. + float32 friction; - /// The restitution (elasticity) usually in the range [0,1]. - float32 restitution; + /// The restitution (elasticity) usually in the range [0,1]. + float32 restitution; - /// The density, usually in kg/m^2. - float32 density; + /// The density, usually in kg/m^2. + float32 density; - /// A sensor shape collects contact information but never generates a collision - /// response. - bool isSensor; + /// A sensor shape collects contact information but never generates a collision + /// response. + bool isSensor; - /// Contact filtering data. - b2Filter filter; + /// Contact filtering data. + b2Filter filter; }; /// This proxy is used internally to connect fixtures to the broad-phase. struct b2FixtureProxy { - b2AABB aabb; - b2Fixture* fixture; - int32 childIndex; - int32 proxyId; + b2AABB aabb; + b2Fixture* fixture; + int32 childIndex; + int32 proxyId; }; /// A fixture is used to attach a shape to a body for collision detection. A fixture @@ -107,239 +107,239 @@ struct b2FixtureProxy class b2Fixture { public: - /// Get the type of the child shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - b2Shape::Type GetType() const; + /// Get the type of the child shape. You can use this to down cast to the concrete shape. + /// @return the shape type. + b2Shape::Type GetType() const; - /// Get the child shape. You can modify the child shape, however you should not change the - /// number of vertices because this will crash some collision caching mechanisms. - /// Manipulating the shape may lead to non-physical behavior. - b2Shape* GetShape(); - const b2Shape* GetShape() const; + /// Get the child shape. You can modify the child shape, however you should not change the + /// number of vertices because this will crash some collision caching mechanisms. + /// Manipulating the shape may lead to non-physical behavior. + b2Shape* GetShape(); + const b2Shape* GetShape() const; - /// Set if this fixture is a sensor. - void SetSensor(bool sensor); + /// Set if this fixture is a sensor. + void SetSensor(bool sensor); - /// Is this fixture a sensor (non-solid)? - /// @return the true if the shape is a sensor. - bool IsSensor() const; + /// Is this fixture a sensor (non-solid)? + /// @return the true if the shape is a sensor. + bool IsSensor() const; - /// Set the contact filtering data. This will not update contacts until the next time - /// step when either parent body is active and awake. - /// This automatically calls Refilter. - void SetFilterData(const b2Filter& filter); + /// Set the contact filtering data. This will not update contacts until the next time + /// step when either parent body is active and awake. + /// This automatically calls Refilter. + void SetFilterData(const b2Filter& filter); - /// Get the contact filtering data. - const b2Filter& GetFilterData() const; + /// Get the contact filtering data. + const b2Filter& GetFilterData() const; - /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. - void Refilter(); + /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. + void Refilter(); - /// Get the parent body of this fixture. This is NULL if the fixture is not attached. - /// @return the parent body. - b2Body* GetBody(); - const b2Body* GetBody() const; + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. + /// @return the parent body. + b2Body* GetBody(); + const b2Body* GetBody() const; - /// Get the next fixture in the parent body's fixture list. - /// @return the next shape. - b2Fixture* GetNext(); - const b2Fixture* GetNext() const; + /// Get the next fixture in the parent body's fixture list. + /// @return the next shape. + b2Fixture* GetNext(); + const b2Fixture* GetNext() const; - /// Get the user data that was assigned in the fixture definition. Use this to - /// store your application specific data. - void* GetUserData() const; + /// Get the user data that was assigned in the fixture definition. Use this to + /// store your application specific data. + void* GetUserData() const; - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); + /// Set the user data. Use this to store your application specific data. + void SetUserData(void* data); - /// Test a point for containment in this fixture. - /// @param p a point in world coordinates. - bool TestPoint(const b2Vec2& p) const; + /// Test a point for containment in this fixture. + /// @param p a point in world coordinates. + bool TestPoint(const b2Vec2& p) const; - /// Cast a ray against this shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; + /// Cast a ray against this shape. + /// @param output the ray-cast results. + /// @param input the ray-cast input parameters. + bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; - /// Get the mass data for this fixture. The mass data is based on the density and - /// the shape. The rotational inertia is about the shape's origin. This operation - /// may be expensive. - void GetMassData(b2MassData* massData) const; + /// Get the mass data for this fixture. The mass data is based on the density and + /// the shape. The rotational inertia is about the shape's origin. This operation + /// may be expensive. + void GetMassData(b2MassData* massData) const; - /// Set the density of this fixture. This will _not_ automatically adjust the mass - /// of the body. You must call b2Body::ResetMassData to update the body's mass. - void SetDensity(float32 density); + /// Set the density of this fixture. This will _not_ automatically adjust the mass + /// of the body. You must call b2Body::ResetMassData to update the body's mass. + void SetDensity(float32 density); - /// Get the density of this fixture. - float32 GetDensity() const; + /// Get the density of this fixture. + float32 GetDensity() const; - /// Get the coefficient of friction. - float32 GetFriction() const; + /// Get the coefficient of friction. + float32 GetFriction() const; - /// Set the coefficient of friction. This will _not_ change the friction of - /// existing contacts. - void SetFriction(float32 friction); + /// Set the coefficient of friction. This will _not_ change the friction of + /// existing contacts. + void SetFriction(float32 friction); - /// Get the coefficient of restitution. - float32 GetRestitution() const; + /// Get the coefficient of restitution. + float32 GetRestitution() const; - /// Set the coefficient of restitution. This will _not_ change the restitution of - /// existing contacts. - void SetRestitution(float32 restitution); + /// Set the coefficient of restitution. This will _not_ change the restitution of + /// existing contacts. + void SetRestitution(float32 restitution); - /// Get the fixture's AABB. This AABB may be enlarge and/or stale. - /// If you need a more accurate AABB, compute it using the shape and - /// the body transform. - const b2AABB& GetAABB(int32 childIndex) const; + /// Get the fixture's AABB. This AABB may be enlarge and/or stale. + /// If you need a more accurate AABB, compute it using the shape and + /// the body transform. + const b2AABB& GetAABB(int32 childIndex) const; - /// Dump this fixture to the log file. - void Dump(int32 bodyIndex); + /// Dump this fixture to the log file. + void Dump(int32 bodyIndex); protected: - friend class b2Body; - friend class b2World; - friend class b2Contact; - friend class b2ContactManager; + friend class b2Body; + friend class b2World; + friend class b2Contact; + friend class b2ContactManager; - b2Fixture(); + b2Fixture(); - // We need separation create/destroy functions from the constructor/destructor because - // the destructor cannot access the allocator (no destructor arguments allowed by C++). - void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); - void Destroy(b2BlockAllocator* allocator); + // We need separation create/destroy functions from the constructor/destructor because + // the destructor cannot access the allocator (no destructor arguments allowed by C++). + void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); + void Destroy(b2BlockAllocator* allocator); - // These support body activation/deactivation. - void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); - void DestroyProxies(b2BroadPhase* broadPhase); + // These support body activation/deactivation. + void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); + void DestroyProxies(b2BroadPhase* broadPhase); - void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); + void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); - float32 m_density; + float32 m_density; - b2Fixture* m_next; - b2Body* m_body; + b2Fixture* m_next; + b2Body* m_body; - b2Shape* m_shape; + b2Shape* m_shape; - float32 m_friction; - float32 m_restitution; + float32 m_friction; + float32 m_restitution; - b2FixtureProxy* m_proxies; - int32 m_proxyCount; + b2FixtureProxy* m_proxies; + int32 m_proxyCount; - b2Filter m_filter; + b2Filter m_filter; - bool m_isSensor; + bool m_isSensor; - void* m_userData; + void* m_userData; }; inline b2Shape::Type b2Fixture::GetType() const { - return m_shape->GetType(); + return m_shape->GetType(); } inline b2Shape* b2Fixture::GetShape() { - return m_shape; + return m_shape; } inline const b2Shape* b2Fixture::GetShape() const { - return m_shape; + return m_shape; } inline bool b2Fixture::IsSensor() const { - return m_isSensor; + return m_isSensor; } inline const b2Filter& b2Fixture::GetFilterData() const { - return m_filter; + return m_filter; } inline void* b2Fixture::GetUserData() const { - return m_userData; + return m_userData; } inline void b2Fixture::SetUserData(void* data) { - m_userData = data; + m_userData = data; } inline b2Body* b2Fixture::GetBody() { - return m_body; + return m_body; } inline const b2Body* b2Fixture::GetBody() const { - return m_body; + return m_body; } inline b2Fixture* b2Fixture::GetNext() { - return m_next; + return m_next; } inline const b2Fixture* b2Fixture::GetNext() const { - return m_next; + return m_next; } inline void b2Fixture::SetDensity(float32 density) { - b2Assert(b2IsValid(density) && density >= 0.0f); - m_density = density; + b2Assert(b2IsValid(density) && density >= 0.0f); + m_density = density; } inline float32 b2Fixture::GetDensity() const { - return m_density; + return m_density; } inline float32 b2Fixture::GetFriction() const { - return m_friction; + return m_friction; } inline void b2Fixture::SetFriction(float32 friction) { - m_friction = friction; + m_friction = friction; } inline float32 b2Fixture::GetRestitution() const { - return m_restitution; + return m_restitution; } inline void b2Fixture::SetRestitution(float32 restitution) { - m_restitution = restitution; + m_restitution = restitution; } inline bool b2Fixture::TestPoint(const b2Vec2& p) const { - return m_shape->TestPoint(m_body->GetTransform(), p); + return m_shape->TestPoint(m_body->GetTransform(), p); } inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const { - return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); + return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); } inline void b2Fixture::GetMassData(b2MassData* massData) const { - m_shape->ComputeMass(massData, m_density); + m_shape->ComputeMass(massData, m_density); } inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const { - b2Assert(0 <= childIndex && childIndex < m_proxyCount); - return m_proxies[childIndex].aabb; + b2Assert(0 <= childIndex && childIndex < m_proxyCount); + return m_proxies[childIndex].aabb; } #endif diff --git a/external/Box2D/Dynamics/b2Island.cpp b/external/Box2D/Dynamics/b2Island.cpp index e767d383d5..d46589dee9 100644 --- a/external/Box2D/Dynamics/b2Island.cpp +++ b/external/Box2D/Dynamics/b2Island.cpp @@ -146,394 +146,394 @@ However, we can compute sin+cos of the same angle fast. */ b2Island::b2Island( - int32 bodyCapacity, - int32 contactCapacity, - int32 jointCapacity, - b2StackAllocator* allocator, - b2ContactListener* listener) + int32 bodyCapacity, + int32 contactCapacity, + int32 jointCapacity, + b2StackAllocator* allocator, + b2ContactListener* listener) { - m_bodyCapacity = bodyCapacity; - m_contactCapacity = contactCapacity; - m_jointCapacity = jointCapacity; - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; + m_bodyCapacity = bodyCapacity; + m_contactCapacity = contactCapacity; + m_jointCapacity = jointCapacity; + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; - m_allocator = allocator; - m_listener = listener; + m_allocator = allocator; + m_listener = listener; - m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); - m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); - m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); + m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); + m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); + m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); - m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); - m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); + m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); + m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); } b2Island::~b2Island() { - // Warning: the order should reverse the constructor order. - m_allocator->Free(m_positions); - m_allocator->Free(m_velocities); - m_allocator->Free(m_joints); - m_allocator->Free(m_contacts); - m_allocator->Free(m_bodies); + // Warning: the order should reverse the constructor order. + m_allocator->Free(m_positions); + m_allocator->Free(m_velocities); + m_allocator->Free(m_joints); + m_allocator->Free(m_contacts); + m_allocator->Free(m_bodies); } void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) { - b2Timer timer; + b2Timer timer; - float32 h = step.dt; + float32 h = step.dt; - // Integrate velocities and apply damping. Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; + // Integrate velocities and apply damping. Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; - b2Vec2 c = b->m_sweep.c; - float32 a = b->m_sweep.a; - b2Vec2 v = b->m_linearVelocity; - float32 w = b->m_angularVelocity; + b2Vec2 c = b->m_sweep.c; + float32 a = b->m_sweep.a; + b2Vec2 v = b->m_linearVelocity; + float32 w = b->m_angularVelocity; - // Store positions for continuous collision. - b->m_sweep.c0 = b->m_sweep.c; - b->m_sweep.a0 = b->m_sweep.a; + // Store positions for continuous collision. + b->m_sweep.c0 = b->m_sweep.c; + b->m_sweep.a0 = b->m_sweep.a; - if (b->m_type == b2_dynamicBody) - { - // Integrate velocities. - v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); - w += h * b->m_invI * b->m_torque; + if (b->m_type == b2_dynamicBody) + { + // Integrate velocities. + v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); + w += h * b->m_invI * b->m_torque; - // Apply damping. - // ODE: dv/dt + c * v = 0 - // Solution: v(t) = v0 * exp(-c * t) - // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) - // v2 = exp(-c * dt) * v1 - // Taylor expansion: - // v2 = (1.0f - c * dt) * v1 - v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); - w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); - } + // Apply damping. + // ODE: dv/dt + c * v = 0 + // Solution: v(t) = v0 * exp(-c * t) + // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) + // v2 = exp(-c * dt) * v1 + // Pade approximation: + // v2 = v1 * 1 / (1 + c * dt) + v *= 1.0f / (1.0f + h * b->m_linearDamping); + w *= 1.0f / (1.0f + h * b->m_angularDamping); + } - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } - timer.Reset(); + timer.Reset(); - // Solver data - b2SolverData solverData; - solverData.step = step; - solverData.positions = m_positions; - solverData.velocities = m_velocities; + // Solver data + b2SolverData solverData; + solverData.step = step; + solverData.positions = m_positions; + solverData.velocities = m_velocities; - // Initialize velocity constraints. - b2ContactSolverDef contactSolverDef; - contactSolverDef.step = step; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - contactSolverDef.allocator = m_allocator; + // Initialize velocity constraints. + b2ContactSolverDef contactSolverDef; + contactSolverDef.step = step; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + contactSolverDef.allocator = m_allocator; - b2ContactSolver contactSolver(&contactSolverDef); - contactSolver.InitializeVelocityConstraints(); + b2ContactSolver contactSolver(&contactSolverDef); + contactSolver.InitializeVelocityConstraints(); - if (step.warmStarting) - { - contactSolver.WarmStart(); - } - - for (int32 i = 0; i < m_jointCount; ++i) - { - m_joints[i]->InitVelocityConstraints(solverData); - } + if (step.warmStarting) + { + contactSolver.WarmStart(); + } + + for (int32 i = 0; i < m_jointCount; ++i) + { + m_joints[i]->InitVelocityConstraints(solverData); + } - profile->solveInit = timer.GetMilliseconds(); + profile->solveInit = timer.GetMilliseconds(); - // Solve velocity constraints - timer.Reset(); - for (int32 i = 0; i < step.velocityIterations; ++i) - { - for (int32 j = 0; j < m_jointCount; ++j) - { - m_joints[j]->SolveVelocityConstraints(solverData); - } + // Solve velocity constraints + timer.Reset(); + for (int32 i = 0; i < step.velocityIterations; ++i) + { + for (int32 j = 0; j < m_jointCount; ++j) + { + m_joints[j]->SolveVelocityConstraints(solverData); + } - contactSolver.SolveVelocityConstraints(); - } + contactSolver.SolveVelocityConstraints(); + } - // Store impulses for warm starting - contactSolver.StoreImpulses(); - profile->solveVelocity = timer.GetMilliseconds(); + // Store impulses for warm starting + contactSolver.StoreImpulses(); + profile->solveVelocity = timer.GetMilliseconds(); - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } - // Integrate - c += h * v; - a += h * w; + // Integrate + c += h * v; + a += h * w; - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; + } - // Solve position constraints - timer.Reset(); - bool positionSolved = false; - for (int32 i = 0; i < step.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolvePositionConstraints(); + // Solve position constraints + timer.Reset(); + bool positionSolved = false; + for (int32 i = 0; i < step.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolvePositionConstraints(); - bool jointsOkay = true; - for (int32 i = 0; i < m_jointCount; ++i) - { - bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); - jointsOkay = jointsOkay && jointOkay; - } + bool jointsOkay = true; + for (int32 i = 0; i < m_jointCount; ++i) + { + bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); + jointsOkay = jointsOkay && jointOkay; + } - if (contactsOkay && jointsOkay) - { - // Exit early if the position errors are small. - positionSolved = true; - break; - } - } + if (contactsOkay && jointsOkay) + { + // Exit early if the position errors are small. + positionSolved = true; + break; + } + } - // Copy state buffers back to the bodies - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* body = m_bodies[i]; - body->m_sweep.c = m_positions[i].c; - body->m_sweep.a = m_positions[i].a; - body->m_linearVelocity = m_velocities[i].v; - body->m_angularVelocity = m_velocities[i].w; - body->SynchronizeTransform(); - } + // Copy state buffers back to the bodies + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* body = m_bodies[i]; + body->m_sweep.c = m_positions[i].c; + body->m_sweep.a = m_positions[i].a; + body->m_linearVelocity = m_velocities[i].v; + body->m_angularVelocity = m_velocities[i].w; + body->SynchronizeTransform(); + } - profile->solvePosition = timer.GetMilliseconds(); + profile->solvePosition = timer.GetMilliseconds(); - Report(contactSolver.m_velocityConstraints); + Report(contactSolver.m_velocityConstraints); - if (allowSleep) - { - float32 minSleepTime = b2_maxFloat; + if (allowSleep) + { + float32 minSleepTime = b2_maxFloat; - const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; - const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; + const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; + const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - continue; - } + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + continue; + } - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || - b->m_angularVelocity * b->m_angularVelocity > angTolSqr || - b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) - { - b->m_sleepTime = 0.0f; - minSleepTime = 0.0f; - } - else - { - b->m_sleepTime += h; - minSleepTime = b2Min(minSleepTime, b->m_sleepTime); - } - } + if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || + b->m_angularVelocity * b->m_angularVelocity > angTolSqr || + b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) + { + b->m_sleepTime = 0.0f; + minSleepTime = 0.0f; + } + else + { + b->m_sleepTime += h; + minSleepTime = b2Min(minSleepTime, b->m_sleepTime); + } + } - if (minSleepTime >= b2_timeToSleep && positionSolved) - { - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - b->SetAwake(false); - } - } - } + if (minSleepTime >= b2_timeToSleep && positionSolved) + { + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + b->SetAwake(false); + } + } + } } void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) { - b2Assert(toiIndexA < m_bodyCount); - b2Assert(toiIndexB < m_bodyCount); + b2Assert(toiIndexA < m_bodyCount); + b2Assert(toiIndexB < m_bodyCount); - // Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - m_positions[i].c = b->m_sweep.c; - m_positions[i].a = b->m_sweep.a; - m_velocities[i].v = b->m_linearVelocity; - m_velocities[i].w = b->m_angularVelocity; - } + // Initialize the body state. + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Body* b = m_bodies[i]; + m_positions[i].c = b->m_sweep.c; + m_positions[i].a = b->m_sweep.a; + m_velocities[i].v = b->m_linearVelocity; + m_velocities[i].w = b->m_angularVelocity; + } - b2ContactSolverDef contactSolverDef; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.allocator = m_allocator; - contactSolverDef.step = subStep; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - b2ContactSolver contactSolver(&contactSolverDef); + b2ContactSolverDef contactSolverDef; + contactSolverDef.contacts = m_contacts; + contactSolverDef.count = m_contactCount; + contactSolverDef.allocator = m_allocator; + contactSolverDef.step = subStep; + contactSolverDef.positions = m_positions; + contactSolverDef.velocities = m_velocities; + b2ContactSolver contactSolver(&contactSolverDef); - // Solve position constraints. - for (int32 i = 0; i < subStep.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); - if (contactsOkay) - { - break; - } - } + // Solve position constraints. + for (int32 i = 0; i < subStep.positionIterations; ++i) + { + bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); + if (contactsOkay) + { + break; + } + } #if 0 - // Is the new position really safe? - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); + // Is the new position really safe? + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); - b2DistanceInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.transformA = bA->GetTransform(); - input.transformB = bB->GetTransform(); - input.useRadii = false; + b2DistanceInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.transformA = bA->GetTransform(); + input.transformB = bB->GetTransform(); + input.useRadii = false; - b2DistanceOutput output; - b2SimplexCache cache; - cache.count = 0; - b2Distance(&output, &cache, &input); + b2DistanceOutput output; + b2SimplexCache cache; + cache.count = 0; + b2Distance(&output, &cache, &input); - if (output.distance == 0 || cache.count == 3) - { - cache.count += 0; - } - } + if (output.distance == 0 || cache.count == 3) + { + cache.count += 0; + } + } #endif - // Leap of faith to new safe state. - m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; - m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; - m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; - m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; + // Leap of faith to new safe state. + m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; + m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; + m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; + m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; - // No warm starting is needed for TOI events because warm - // starting impulses were applied in the discrete solver. - contactSolver.InitializeVelocityConstraints(); + // No warm starting is needed for TOI events because warm + // starting impulses were applied in the discrete solver. + contactSolver.InitializeVelocityConstraints(); - // Solve velocity constraints. - for (int32 i = 0; i < subStep.velocityIterations; ++i) - { - contactSolver.SolveVelocityConstraints(); - } + // Solve velocity constraints. + for (int32 i = 0; i < subStep.velocityIterations; ++i) + { + contactSolver.SolveVelocityConstraints(); + } - // Don't store the TOI contact forces for warm starting - // because they can be quite large. + // Don't store the TOI contact forces for warm starting + // because they can be quite large. - float32 h = subStep.dt; + float32 h = subStep.dt; - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; + // Integrate positions + for (int32 i = 0; i < m_bodyCount; ++i) + { + b2Vec2 c = m_positions[i].c; + float32 a = m_positions[i].a; + b2Vec2 v = m_velocities[i].v; + float32 w = m_velocities[i].w; - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } + // Check for large velocities + b2Vec2 translation = h * v; + if (b2Dot(translation, translation) > b2_maxTranslationSquared) + { + float32 ratio = b2_maxTranslation / translation.Length(); + v *= ratio; + } - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } + float32 rotation = h * w; + if (rotation * rotation > b2_maxRotationSquared) + { + float32 ratio = b2_maxRotation / b2Abs(rotation); + w *= ratio; + } - // Integrate - c += h * v; - a += h * w; + // Integrate + c += h * v; + a += h * w; - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; + m_positions[i].c = c; + m_positions[i].a = a; + m_velocities[i].v = v; + m_velocities[i].w = w; - // Sync bodies - b2Body* body = m_bodies[i]; - body->m_sweep.c = c; - body->m_sweep.a = a; - body->m_linearVelocity = v; - body->m_angularVelocity = w; - body->SynchronizeTransform(); - } + // Sync bodies + b2Body* body = m_bodies[i]; + body->m_sweep.c = c; + body->m_sweep.a = a; + body->m_linearVelocity = v; + body->m_angularVelocity = w; + body->SynchronizeTransform(); + } - Report(contactSolver.m_velocityConstraints); + Report(contactSolver.m_velocityConstraints); } void b2Island::Report(const b2ContactVelocityConstraint* constraints) { - if (m_listener == NULL) - { - return; - } + if (m_listener == NULL) + { + return; + } - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; + for (int32 i = 0; i < m_contactCount; ++i) + { + b2Contact* c = m_contacts[i]; - const b2ContactVelocityConstraint* vc = constraints + i; - - b2ContactImpulse impulse; - impulse.count = vc->pointCount; - for (int32 j = 0; j < vc->pointCount; ++j) - { - impulse.normalImpulses[j] = vc->points[j].normalImpulse; - impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; - } + const b2ContactVelocityConstraint* vc = constraints + i; + + b2ContactImpulse impulse; + impulse.count = vc->pointCount; + for (int32 j = 0; j < vc->pointCount; ++j) + { + impulse.normalImpulses[j] = vc->points[j].normalImpulse; + impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; + } - m_listener->PostSolve(c, &impulse); - } + m_listener->PostSolve(c, &impulse); + } } diff --git a/external/Box2D/Dynamics/b2Island.h b/external/Box2D/Dynamics/b2Island.h index e0a6e41fc3..4a814c463e 100644 --- a/external/Box2D/Dynamics/b2Island.h +++ b/external/Box2D/Dynamics/b2Island.h @@ -34,60 +34,60 @@ struct b2Profile; class b2Island { public: - b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, - b2StackAllocator* allocator, b2ContactListener* listener); - ~b2Island(); + b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, + b2StackAllocator* allocator, b2ContactListener* listener); + ~b2Island(); - void Clear() - { - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - } + void Clear() + { + m_bodyCount = 0; + m_contactCount = 0; + m_jointCount = 0; + } - void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); + void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); - void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); + void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); - void Add(b2Body* body) - { - b2Assert(m_bodyCount < m_bodyCapacity); - body->m_islandIndex = m_bodyCount; - m_bodies[m_bodyCount] = body; - ++m_bodyCount; - } + void Add(b2Body* body) + { + b2Assert(m_bodyCount < m_bodyCapacity); + body->m_islandIndex = m_bodyCount; + m_bodies[m_bodyCount] = body; + ++m_bodyCount; + } - void Add(b2Contact* contact) - { - b2Assert(m_contactCount < m_contactCapacity); - m_contacts[m_contactCount++] = contact; - } + void Add(b2Contact* contact) + { + b2Assert(m_contactCount < m_contactCapacity); + m_contacts[m_contactCount++] = contact; + } - void Add(b2Joint* joint) - { - b2Assert(m_jointCount < m_jointCapacity); - m_joints[m_jointCount++] = joint; - } + void Add(b2Joint* joint) + { + b2Assert(m_jointCount < m_jointCapacity); + m_joints[m_jointCount++] = joint; + } - void Report(const b2ContactVelocityConstraint* constraints); + void Report(const b2ContactVelocityConstraint* constraints); - b2StackAllocator* m_allocator; - b2ContactListener* m_listener; + b2StackAllocator* m_allocator; + b2ContactListener* m_listener; - b2Body** m_bodies; - b2Contact** m_contacts; - b2Joint** m_joints; + b2Body** m_bodies; + b2Contact** m_contacts; + b2Joint** m_joints; - b2Position* m_positions; - b2Velocity* m_velocities; + b2Position* m_positions; + b2Velocity* m_velocities; - int32 m_bodyCount; - int32 m_jointCount; - int32 m_contactCount; + int32 m_bodyCount; + int32 m_jointCount; + int32 m_contactCount; - int32 m_bodyCapacity; - int32 m_contactCapacity; - int32 m_jointCapacity; + int32 m_bodyCapacity; + int32 m_contactCapacity; + int32 m_jointCapacity; }; #endif diff --git a/external/Box2D/Dynamics/b2TimeStep.h b/external/Box2D/Dynamics/b2TimeStep.h index 30d723fcc3..a3727624cd 100644 --- a/external/Box2D/Dynamics/b2TimeStep.h +++ b/external/Box2D/Dynamics/b2TimeStep.h @@ -24,47 +24,47 @@ /// Profiling data. Times are in milliseconds. struct b2Profile { - float32 step; - float32 collide; - float32 solve; - float32 solveInit; - float32 solveVelocity; - float32 solvePosition; - float32 broadphase; - float32 solveTOI; + float32 step; + float32 collide; + float32 solve; + float32 solveInit; + float32 solveVelocity; + float32 solvePosition; + float32 broadphase; + float32 solveTOI; }; /// This is an internal structure. struct b2TimeStep { - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 velocityIterations; - int32 positionIterations; - bool warmStarting; + float32 dt; // time step + float32 inv_dt; // inverse time step (0 if dt == 0). + float32 dtRatio; // dt * inv_dt0 + int32 velocityIterations; + int32 positionIterations; + bool warmStarting; }; /// This is an internal structure. struct b2Position { - b2Vec2 c; - float32 a; + b2Vec2 c; + float32 a; }; /// This is an internal structure. struct b2Velocity { - b2Vec2 v; - float32 w; + b2Vec2 v; + float32 w; }; /// Solver Data struct b2SolverData { - b2TimeStep step; - b2Position* positions; - b2Velocity* velocities; + b2TimeStep step; + b2Position* positions; + b2Velocity* velocities; }; #endif diff --git a/external/Box2D/Dynamics/b2World.cpp b/external/Box2D/Dynamics/b2World.cpp index 8a0aff5114..a3a6a1e413 100644 --- a/external/Box2D/Dynamics/b2World.cpp +++ b/external/Box2D/Dynamics/b2World.cpp @@ -36,1281 +36,1304 @@ b2World::b2World(const b2Vec2& gravity) { - m_destructionListener = NULL; - m_debugDraw = NULL; + m_destructionListener = NULL; + m_debugDraw = NULL; - m_bodyList = NULL; - m_jointList = NULL; + m_bodyList = NULL; + m_jointList = NULL; - m_bodyCount = 0; - m_jointCount = 0; + m_bodyCount = 0; + m_jointCount = 0; - m_warmStarting = true; - m_continuousPhysics = true; - m_subStepping = false; + m_warmStarting = true; + m_continuousPhysics = true; + m_subStepping = false; - m_stepComplete = true; + m_stepComplete = true; - m_allowSleep = true; - m_gravity = gravity; + m_allowSleep = true; + m_gravity = gravity; - m_flags = e_clearForces; + m_flags = e_clearForces; - m_inv_dt0 = 0.0f; + m_inv_dt0 = 0.0f; - m_contactManager.m_allocator = &m_blockAllocator; + m_contactManager.m_allocator = &m_blockAllocator; - memset(&m_profile, 0, sizeof(b2Profile)); + memset(&m_profile, 0, sizeof(b2Profile)); } b2World::~b2World() { - // Some shapes allocate using b2Alloc. - b2Body* b = m_bodyList; - while (b) - { - b2Body* bNext = b->m_next; + // Some shapes allocate using b2Alloc. + b2Body* b = m_bodyList; + while (b) + { + b2Body* bNext = b->m_next; - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* fNext = f->m_next; - f->m_proxyCount = 0; - f->Destroy(&m_blockAllocator); - f = fNext; - } + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* fNext = f->m_next; + f->m_proxyCount = 0; + f->Destroy(&m_blockAllocator); + f = fNext; + } - b = bNext; - } + b = bNext; + } } void b2World::SetDestructionListener(b2DestructionListener* listener) { - m_destructionListener = listener; + m_destructionListener = listener; } void b2World::SetContactFilter(b2ContactFilter* filter) { - m_contactManager.m_contactFilter = filter; + m_contactManager.m_contactFilter = filter; } void b2World::SetContactListener(b2ContactListener* listener) { - m_contactManager.m_contactListener = listener; + m_contactManager.m_contactListener = listener; } void b2World::SetDebugDraw(b2Draw* debugDraw) { - m_debugDraw = debugDraw; + m_debugDraw = debugDraw; } b2Body* b2World::CreateBody(const b2BodyDef* def) { - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } - void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); - b2Body* b = new (mem) b2Body(def, this); + void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); + b2Body* b = new (mem) b2Body(def, this); - // Add to world doubly linked list. - b->m_prev = NULL; - b->m_next = m_bodyList; - if (m_bodyList) - { - m_bodyList->m_prev = b; - } - m_bodyList = b; - ++m_bodyCount; + // Add to world doubly linked list. + b->m_prev = NULL; + b->m_next = m_bodyList; + if (m_bodyList) + { + m_bodyList->m_prev = b; + } + m_bodyList = b; + ++m_bodyCount; - return b; + return b; } void b2World::DestroyBody(b2Body* b) { - b2Assert(m_bodyCount > 0); - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } + b2Assert(m_bodyCount > 0); + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } - // Delete the attached joints. - b2JointEdge* je = b->m_jointList; - while (je) - { - b2JointEdge* je0 = je; - je = je->next; + // Delete the attached joints. + b2JointEdge* je = b->m_jointList; + while (je) + { + b2JointEdge* je0 = je; + je = je->next; - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(je0->joint); - } + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(je0->joint); + } - DestroyJoint(je0->joint); + DestroyJoint(je0->joint); - b->m_jointList = je; - } - b->m_jointList = NULL; + b->m_jointList = je; + } + b->m_jointList = NULL; - // Delete the attached contacts. - b2ContactEdge* ce = b->m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_contactManager.Destroy(ce0->contact); - } - b->m_contactList = NULL; + // Delete the attached contacts. + b2ContactEdge* ce = b->m_contactList; + while (ce) + { + b2ContactEdge* ce0 = ce; + ce = ce->next; + m_contactManager.Destroy(ce0->contact); + } + b->m_contactList = NULL; - // Delete the attached fixtures. This destroys broad-phase proxies. - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* f0 = f; - f = f->m_next; + // Delete the attached fixtures. This destroys broad-phase proxies. + b2Fixture* f = b->m_fixtureList; + while (f) + { + b2Fixture* f0 = f; + f = f->m_next; - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(f0); - } + if (m_destructionListener) + { + m_destructionListener->SayGoodbye(f0); + } - f0->DestroyProxies(&m_contactManager.m_broadPhase); - f0->Destroy(&m_blockAllocator); - f0->~b2Fixture(); - m_blockAllocator.Free(f0, sizeof(b2Fixture)); + f0->DestroyProxies(&m_contactManager.m_broadPhase); + f0->Destroy(&m_blockAllocator); + f0->~b2Fixture(); + m_blockAllocator.Free(f0, sizeof(b2Fixture)); - b->m_fixtureList = f; - b->m_fixtureCount -= 1; - } - b->m_fixtureList = NULL; - b->m_fixtureCount = 0; + b->m_fixtureList = f; + b->m_fixtureCount -= 1; + } + b->m_fixtureList = NULL; + b->m_fixtureCount = 0; - // Remove world body list. - if (b->m_prev) - { - b->m_prev->m_next = b->m_next; - } + // Remove world body list. + if (b->m_prev) + { + b->m_prev->m_next = b->m_next; + } - if (b->m_next) - { - b->m_next->m_prev = b->m_prev; - } + if (b->m_next) + { + b->m_next->m_prev = b->m_prev; + } - if (b == m_bodyList) - { - m_bodyList = b->m_next; - } + if (b == m_bodyList) + { + m_bodyList = b->m_next; + } - --m_bodyCount; - b->~b2Body(); - m_blockAllocator.Free(b, sizeof(b2Body)); + --m_bodyCount; + b->~b2Body(); + m_blockAllocator.Free(b, sizeof(b2Body)); } b2Joint* b2World::CreateJoint(const b2JointDef* def) { - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return NULL; - } + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return NULL; + } - b2Joint* j = b2Joint::Create(def, &m_blockAllocator); + b2Joint* j = b2Joint::Create(def, &m_blockAllocator); - // Connect to the world list. - j->m_prev = NULL; - j->m_next = m_jointList; - if (m_jointList) - { - m_jointList->m_prev = j; - } - m_jointList = j; - ++m_jointCount; + // Connect to the world list. + j->m_prev = NULL; + j->m_next = m_jointList; + if (m_jointList) + { + m_jointList->m_prev = j; + } + m_jointList = j; + ++m_jointCount; - // Connect to the bodies' doubly linked lists. - j->m_edgeA.joint = j; - j->m_edgeA.other = j->m_bodyB; - j->m_edgeA.prev = NULL; - j->m_edgeA.next = j->m_bodyA->m_jointList; - if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; - j->m_bodyA->m_jointList = &j->m_edgeA; + // Connect to the bodies' doubly linked lists. + j->m_edgeA.joint = j; + j->m_edgeA.other = j->m_bodyB; + j->m_edgeA.prev = NULL; + j->m_edgeA.next = j->m_bodyA->m_jointList; + if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; + j->m_bodyA->m_jointList = &j->m_edgeA; - j->m_edgeB.joint = j; - j->m_edgeB.other = j->m_bodyA; - j->m_edgeB.prev = NULL; - j->m_edgeB.next = j->m_bodyB->m_jointList; - if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; - j->m_bodyB->m_jointList = &j->m_edgeB; + j->m_edgeB.joint = j; + j->m_edgeB.other = j->m_bodyA; + j->m_edgeB.prev = NULL; + j->m_edgeB.next = j->m_bodyB->m_jointList; + if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; + j->m_bodyB->m_jointList = &j->m_edgeB; - b2Body* bodyA = def->bodyA; - b2Body* bodyB = def->bodyB; + b2Body* bodyA = def->bodyA; + b2Body* bodyB = def->bodyB; - // If the joint prevents collisions, then flag any contacts for filtering. - if (def->collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } + // If the joint prevents collisions, then flag any contacts for filtering. + if (def->collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } - edge = edge->next; - } - } + edge = edge->next; + } + } - // Note: creating a joint doesn't wake the bodies. + // Note: creating a joint doesn't wake the bodies. - return j; + return j; } void b2World::DestroyJoint(b2Joint* j) { - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } + b2Assert(IsLocked() == false); + if (IsLocked()) + { + return; + } - bool collideConnected = j->m_collideConnected; + bool collideConnected = j->m_collideConnected; - // Remove from the doubly linked list. - if (j->m_prev) - { - j->m_prev->m_next = j->m_next; - } + // Remove from the doubly linked list. + if (j->m_prev) + { + j->m_prev->m_next = j->m_next; + } - if (j->m_next) - { - j->m_next->m_prev = j->m_prev; - } + if (j->m_next) + { + j->m_next->m_prev = j->m_prev; + } - if (j == m_jointList) - { - m_jointList = j->m_next; - } + if (j == m_jointList) + { + m_jointList = j->m_next; + } - // Disconnect from island graph. - b2Body* bodyA = j->m_bodyA; - b2Body* bodyB = j->m_bodyB; + // Disconnect from island graph. + b2Body* bodyA = j->m_bodyA; + b2Body* bodyB = j->m_bodyB; - // Wake up connected bodies. - bodyA->SetAwake(true); - bodyB->SetAwake(true); + // Wake up connected bodies. + bodyA->SetAwake(true); + bodyB->SetAwake(true); - // Remove from body 1. - if (j->m_edgeA.prev) - { - j->m_edgeA.prev->next = j->m_edgeA.next; - } + // Remove from body 1. + if (j->m_edgeA.prev) + { + j->m_edgeA.prev->next = j->m_edgeA.next; + } - if (j->m_edgeA.next) - { - j->m_edgeA.next->prev = j->m_edgeA.prev; - } + if (j->m_edgeA.next) + { + j->m_edgeA.next->prev = j->m_edgeA.prev; + } - if (&j->m_edgeA == bodyA->m_jointList) - { - bodyA->m_jointList = j->m_edgeA.next; - } + if (&j->m_edgeA == bodyA->m_jointList) + { + bodyA->m_jointList = j->m_edgeA.next; + } - j->m_edgeA.prev = NULL; - j->m_edgeA.next = NULL; + j->m_edgeA.prev = NULL; + j->m_edgeA.next = NULL; - // Remove from body 2 - if (j->m_edgeB.prev) - { - j->m_edgeB.prev->next = j->m_edgeB.next; - } + // Remove from body 2 + if (j->m_edgeB.prev) + { + j->m_edgeB.prev->next = j->m_edgeB.next; + } - if (j->m_edgeB.next) - { - j->m_edgeB.next->prev = j->m_edgeB.prev; - } + if (j->m_edgeB.next) + { + j->m_edgeB.next->prev = j->m_edgeB.prev; + } - if (&j->m_edgeB == bodyB->m_jointList) - { - bodyB->m_jointList = j->m_edgeB.next; - } + if (&j->m_edgeB == bodyB->m_jointList) + { + bodyB->m_jointList = j->m_edgeB.next; + } - j->m_edgeB.prev = NULL; - j->m_edgeB.next = NULL; + j->m_edgeB.prev = NULL; + j->m_edgeB.next = NULL; - b2Joint::Destroy(j, &m_blockAllocator); + b2Joint::Destroy(j, &m_blockAllocator); - b2Assert(m_jointCount > 0); - --m_jointCount; + b2Assert(m_jointCount > 0); + --m_jointCount; - // If the joint prevents collisions, then flag any contacts for filtering. - if (collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } + // If the joint prevents collisions, then flag any contacts for filtering. + if (collideConnected == false) + { + b2ContactEdge* edge = bodyB->GetContactList(); + while (edge) + { + if (edge->other == bodyA) + { + // Flag the contact for filtering at the next time step (where either + // body is awake). + edge->contact->FlagForFiltering(); + } - edge = edge->next; - } - } + edge = edge->next; + } + } } // void b2World::SetAllowSleeping(bool flag) { - if (flag == m_allowSleep) - { - return; - } + if (flag == m_allowSleep) + { + return; + } - m_allowSleep = flag; - if (m_allowSleep == false) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->SetAwake(true); - } - } + m_allowSleep = flag; + if (m_allowSleep == false) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->SetAwake(true); + } + } } // Find islands, integrate and solve constraints, solve position constraints void b2World::Solve(const b2TimeStep& step) { - m_profile.solveInit = 0.0f; - m_profile.solveVelocity = 0.0f; - m_profile.solvePosition = 0.0f; + m_profile.solveInit = 0.0f; + m_profile.solveVelocity = 0.0f; + m_profile.solvePosition = 0.0f; - // Size the island for the worst case. - b2Island island(m_bodyCount, - m_contactManager.m_contactCount, - m_jointCount, - &m_stackAllocator, - m_contactManager.m_contactListener); + // Size the island for the worst case. + b2Island island(m_bodyCount, + m_contactManager.m_contactCount, + m_jointCount, + &m_stackAllocator, + m_contactManager.m_contactListener); - // Clear all the island flags. - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - c->m_flags &= ~b2Contact::e_islandFlag; - } - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_islandFlag = false; - } + // Clear all the island flags. + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + c->m_flags &= ~b2Contact::e_islandFlag; + } + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_islandFlag = false; + } - // Build and simulate all awake islands. - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) - { - if (seed->m_flags & b2Body::e_islandFlag) - { - continue; - } + // Build and simulate all awake islands. + int32 stackSize = m_bodyCount; + b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); + for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) + { + if (seed->m_flags & b2Body::e_islandFlag) + { + continue; + } - if (seed->IsAwake() == false || seed->IsActive() == false) - { - continue; - } + if (seed->IsAwake() == false || seed->IsActive() == false) + { + continue; + } - // The seed can be dynamic or kinematic. - if (seed->GetType() == b2_staticBody) - { - continue; - } + // The seed can be dynamic or kinematic. + if (seed->GetType() == b2_staticBody) + { + continue; + } - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; + // Reset island and stack. + island.Clear(); + int32 stackCount = 0; + stack[stackCount++] = seed; + seed->m_flags |= b2Body::e_islandFlag; - // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - b2Assert(b->IsActive() == true); - island.Add(b); + // Perform a depth first search (DFS) on the constraint graph. + while (stackCount > 0) + { + // Grab the next body off the stack and add it to the island. + b2Body* b = stack[--stackCount]; + b2Assert(b->IsActive() == true); + island.Add(b); - // Make sure the body is awake. - b->SetAwake(true); + // Make sure the body is awake. + b->SetAwake(true); - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->GetType() == b2_staticBody) - { - continue; - } + // To keep islands as small as possible, we don't + // propagate islands across static bodies. + if (b->GetType() == b2_staticBody) + { + continue; + } - // Search all contacts connected to this body. - for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) - { - b2Contact* contact = ce->contact; + // Search all contacts connected to this body. + for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) + { + b2Contact* contact = ce->contact; - // Has this contact already been added to an island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } + // Has this contact already been added to an island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } - // Is this contact solid and touching? - if (contact->IsEnabled() == false || - contact->IsTouching() == false) - { - continue; - } + // Is this contact solid and touching? + if (contact->IsEnabled() == false || + contact->IsTouching() == false) + { + continue; + } - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } - island.Add(contact); - contact->m_flags |= b2Contact::e_islandFlag; + island.Add(contact); + contact->m_flags |= b2Contact::e_islandFlag; - b2Body* other = ce->other; + b2Body* other = ce->other; - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } + // Was the other body already added to this island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } - // Search all joints connect to this body. - for (b2JointEdge* je = b->m_jointList; je; je = je->next) - { - if (je->joint->m_islandFlag == true) - { - continue; - } + // Search all joints connect to this body. + for (b2JointEdge* je = b->m_jointList; je; je = je->next) + { + if (je->joint->m_islandFlag == true) + { + continue; + } - b2Body* other = je->other; + b2Body* other = je->other; - // Don't simulate joints connected to inactive bodies. - if (other->IsActive() == false) - { - continue; - } + // Don't simulate joints connected to inactive bodies. + if (other->IsActive() == false) + { + continue; + } - island.Add(je->joint); - je->joint->m_islandFlag = true; + island.Add(je->joint); + je->joint->m_islandFlag = true; - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } + b2Assert(stackCount < stackSize); + stack[stackCount++] = other; + other->m_flags |= b2Body::e_islandFlag; + } + } - b2Profile profile; - island.Solve(&profile, step, m_gravity, m_allowSleep); - m_profile.solveInit += profile.solveInit; - m_profile.solveVelocity += profile.solveVelocity; - m_profile.solvePosition += profile.solvePosition; + b2Profile profile; + island.Solve(&profile, step, m_gravity, m_allowSleep); + m_profile.solveInit += profile.solveInit; + m_profile.solveVelocity += profile.solveVelocity; + m_profile.solvePosition += profile.solvePosition; - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow static bodies to participate in other islands. - b2Body* b = island.m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - } - } + // Post solve cleanup. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + // Allow static bodies to participate in other islands. + b2Body* b = island.m_bodies[i]; + if (b->GetType() == b2_staticBody) + { + b->m_flags &= ~b2Body::e_islandFlag; + } + } + } - m_stackAllocator.Free(stack); + m_stackAllocator.Free(stack); - { - b2Timer timer; - // Synchronize fixtures, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - // If a body was not in an island then it did not move. - if ((b->m_flags & b2Body::e_islandFlag) == 0) - { - continue; - } + { + b2Timer timer; + // Synchronize fixtures, check for out of range bodies. + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + // If a body was not in an island then it did not move. + if ((b->m_flags & b2Body::e_islandFlag) == 0) + { + continue; + } - if (b->GetType() == b2_staticBody) - { - continue; - } + if (b->GetType() == b2_staticBody) + { + continue; + } - // Update fixtures (for broad-phase). - b->SynchronizeFixtures(); - } + // Update fixtures (for broad-phase). + b->SynchronizeFixtures(); + } - // Look for new contacts. - m_contactManager.FindNewContacts(); - m_profile.broadphase = timer.GetMilliseconds(); - } + // Look for new contacts. + m_contactManager.FindNewContacts(); + m_profile.broadphase = timer.GetMilliseconds(); + } } // Find TOI contacts and solve them. void b2World::SolveTOI(const b2TimeStep& step) { - b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); + b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); - if (m_stepComplete) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - b->m_sweep.alpha0 = 0.0f; - } + if (m_stepComplete) + { + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_flags &= ~b2Body::e_islandFlag; + b->m_sweep.alpha0 = 0.0f; + } - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Invalidate TOI - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - c->m_toiCount = 0; - c->m_toi = 1.0f; - } - } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Invalidate TOI + c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + c->m_toiCount = 0; + c->m_toi = 1.0f; + } + } - // Find TOI events and solve them. - for (;;) - { - // Find the first TOI. - b2Contact* minContact = NULL; - float32 minAlpha = 1.0f; + // Find TOI events and solve them. + for (;;) + { + // Find the first TOI. + b2Contact* minContact = NULL; + float32 minAlpha = 1.0f; - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Is this contact disabled? - if (c->IsEnabled() == false) - { - continue; - } + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) + { + // Is this contact disabled? + if (c->IsEnabled() == false) + { + continue; + } - // Prevent excessive sub-stepping. - if (c->m_toiCount > b2_maxSubSteps) - { - continue; - } + // Prevent excessive sub-stepping. + if (c->m_toiCount > b2_maxSubSteps) + { + continue; + } - float32 alpha = 1.0f; - if (c->m_flags & b2Contact::e_toiFlag) - { - // This contact has a valid cached TOI. - alpha = c->m_toi; - } - else - { - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); + float32 alpha = 1.0f; + if (c->m_flags & b2Contact::e_toiFlag) + { + // This contact has a valid cached TOI. + alpha = c->m_toi; + } + else + { + b2Fixture* fA = c->GetFixtureA(); + b2Fixture* fB = c->GetFixtureB(); - // Is there a sensor? - if (fA->IsSensor() || fB->IsSensor()) - { - continue; - } + // Is there a sensor? + if (fA->IsSensor() || fB->IsSensor()) + { + continue; + } - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); - b2BodyType typeA = bA->m_type; - b2BodyType typeB = bB->m_type; - b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); + b2BodyType typeA = bA->m_type; + b2BodyType typeB = bB->m_type; + b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); - bool activeA = bA->IsAwake() && typeA != b2_staticBody; - bool activeB = bB->IsAwake() && typeB != b2_staticBody; + bool activeA = bA->IsAwake() && typeA != b2_staticBody; + bool activeB = bB->IsAwake() && typeB != b2_staticBody; - // Is at least one body active (awake and dynamic or kinematic)? - if (activeA == false && activeB == false) - { - continue; - } + // Is at least one body active (awake and dynamic or kinematic)? + if (activeA == false && activeB == false) + { + continue; + } - bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; - bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; + bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; + bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; - // Are these two non-bullet dynamic bodies? - if (collideA == false && collideB == false) - { - continue; - } + // Are these two non-bullet dynamic bodies? + if (collideA == false && collideB == false) + { + continue; + } - // Compute the TOI for this contact. - // Put the sweeps onto the same time interval. - float32 alpha0 = bA->m_sweep.alpha0; + // Compute the TOI for this contact. + // Put the sweeps onto the same time interval. + float32 alpha0 = bA->m_sweep.alpha0; - if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) - { - alpha0 = bB->m_sweep.alpha0; - bA->m_sweep.Advance(alpha0); - } - else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) - { - alpha0 = bA->m_sweep.alpha0; - bB->m_sweep.Advance(alpha0); - } + if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) + { + alpha0 = bB->m_sweep.alpha0; + bA->m_sweep.Advance(alpha0); + } + else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) + { + alpha0 = bA->m_sweep.alpha0; + bB->m_sweep.Advance(alpha0); + } - b2Assert(alpha0 < 1.0f); + b2Assert(alpha0 < 1.0f); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); + int32 indexA = c->GetChildIndexA(); + int32 indexB = c->GetChildIndexB(); - // Compute the time of impact in interval [0, minTOI] - b2TOIInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.sweepA = bA->m_sweep; - input.sweepB = bB->m_sweep; - input.tMax = 1.0f; + // Compute the time of impact in interval [0, minTOI] + b2TOIInput input; + input.proxyA.Set(fA->GetShape(), indexA); + input.proxyB.Set(fB->GetShape(), indexB); + input.sweepA = bA->m_sweep; + input.sweepB = bB->m_sweep; + input.tMax = 1.0f; - b2TOIOutput output; - b2TimeOfImpact(&output, &input); + b2TOIOutput output; + b2TimeOfImpact(&output, &input); - // Beta is the fraction of the remaining portion of the . - float32 beta = output.t; - if (output.state == b2TOIOutput::e_touching) - { - alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); - } - else - { - alpha = 1.0f; - } + // Beta is the fraction of the remaining portion of the . + float32 beta = output.t; + if (output.state == b2TOIOutput::e_touching) + { + alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); + } + else + { + alpha = 1.0f; + } - c->m_toi = alpha; - c->m_flags |= b2Contact::e_toiFlag; - } + c->m_toi = alpha; + c->m_flags |= b2Contact::e_toiFlag; + } - if (alpha < minAlpha) - { - // This is the minimum TOI found so far. - minContact = c; - minAlpha = alpha; - } - } + if (alpha < minAlpha) + { + // This is the minimum TOI found so far. + minContact = c; + minAlpha = alpha; + } + } - if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) - { - // No more TOI events. Done! - m_stepComplete = true; - break; - } + if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) + { + // No more TOI events. Done! + m_stepComplete = true; + break; + } - // Advance the bodies to the TOI. - b2Fixture* fA = minContact->GetFixtureA(); - b2Fixture* fB = minContact->GetFixtureB(); - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); + // Advance the bodies to the TOI. + b2Fixture* fA = minContact->GetFixtureA(); + b2Fixture* fB = minContact->GetFixtureB(); + b2Body* bA = fA->GetBody(); + b2Body* bB = fB->GetBody(); - b2Sweep backup1 = bA->m_sweep; - b2Sweep backup2 = bB->m_sweep; + b2Sweep backup1 = bA->m_sweep; + b2Sweep backup2 = bB->m_sweep; - bA->Advance(minAlpha); - bB->Advance(minAlpha); + bA->Advance(minAlpha); + bB->Advance(minAlpha); - // The TOI contact likely has some new contact points. - minContact->Update(m_contactManager.m_contactListener); - minContact->m_flags &= ~b2Contact::e_toiFlag; - ++minContact->m_toiCount; + // The TOI contact likely has some new contact points. + minContact->Update(m_contactManager.m_contactListener); + minContact->m_flags &= ~b2Contact::e_toiFlag; + ++minContact->m_toiCount; - // Is the contact solid? - if (minContact->IsEnabled() == false || minContact->IsTouching() == false) - { - // Restore the sweeps. - minContact->SetEnabled(false); - bA->m_sweep = backup1; - bB->m_sweep = backup2; - bA->SynchronizeTransform(); - bB->SynchronizeTransform(); - continue; - } + // Is the contact solid? + if (minContact->IsEnabled() == false || minContact->IsTouching() == false) + { + // Restore the sweeps. + minContact->SetEnabled(false); + bA->m_sweep = backup1; + bB->m_sweep = backup2; + bA->SynchronizeTransform(); + bB->SynchronizeTransform(); + continue; + } - bA->SetAwake(true); - bB->SetAwake(true); + bA->SetAwake(true); + bB->SetAwake(true); - // Build the island - island.Clear(); - island.Add(bA); - island.Add(bB); - island.Add(minContact); + // Build the island + island.Clear(); + island.Add(bA); + island.Add(bB); + island.Add(minContact); - bA->m_flags |= b2Body::e_islandFlag; - bB->m_flags |= b2Body::e_islandFlag; - minContact->m_flags |= b2Contact::e_islandFlag; + bA->m_flags |= b2Body::e_islandFlag; + bB->m_flags |= b2Body::e_islandFlag; + minContact->m_flags |= b2Contact::e_islandFlag; - // Get contacts on bodyA and bodyB. - b2Body* bodies[2] = {bA, bB}; - for (int32 i = 0; i < 2; ++i) - { - b2Body* body = bodies[i]; - if (body->m_type == b2_dynamicBody) - { - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - if (island.m_bodyCount == island.m_bodyCapacity) - { - break; - } + // Get contacts on bodyA and bodyB. + b2Body* bodies[2] = {bA, bB}; + for (int32 i = 0; i < 2; ++i) + { + b2Body* body = bodies[i]; + if (body->m_type == b2_dynamicBody) + { + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + if (island.m_bodyCount == island.m_bodyCapacity) + { + break; + } - if (island.m_contactCount == island.m_contactCapacity) - { - break; - } + if (island.m_contactCount == island.m_contactCapacity) + { + break; + } - b2Contact* contact = ce->contact; + b2Contact* contact = ce->contact; - // Has this contact already been added to the island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } + // Has this contact already been added to the island? + if (contact->m_flags & b2Contact::e_islandFlag) + { + continue; + } - // Only add static, kinematic, or bullet bodies. - b2Body* other = ce->other; - if (other->m_type == b2_dynamicBody && - body->IsBullet() == false && other->IsBullet() == false) - { - continue; - } + // Only add static, kinematic, or bullet bodies. + b2Body* other = ce->other; + if (other->m_type == b2_dynamicBody && + body->IsBullet() == false && other->IsBullet() == false) + { + continue; + } - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } + // Skip sensors. + bool sensorA = contact->m_fixtureA->m_isSensor; + bool sensorB = contact->m_fixtureB->m_isSensor; + if (sensorA || sensorB) + { + continue; + } - // Tentatively advance the body to the TOI. - b2Sweep backup = other->m_sweep; - if ((other->m_flags & b2Body::e_islandFlag) == 0) - { - other->Advance(minAlpha); - } + // Tentatively advance the body to the TOI. + b2Sweep backup = other->m_sweep; + if ((other->m_flags & b2Body::e_islandFlag) == 0) + { + other->Advance(minAlpha); + } - // Update the contact points - contact->Update(m_contactManager.m_contactListener); + // Update the contact points + contact->Update(m_contactManager.m_contactListener); - // Was the contact disabled by the user? - if (contact->IsEnabled() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } + // Was the contact disabled by the user? + if (contact->IsEnabled() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } - // Are there contact points? - if (contact->IsTouching() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } + // Are there contact points? + if (contact->IsTouching() == false) + { + other->m_sweep = backup; + other->SynchronizeTransform(); + continue; + } - // Add the contact to the island - contact->m_flags |= b2Contact::e_islandFlag; - island.Add(contact); + // Add the contact to the island + contact->m_flags |= b2Contact::e_islandFlag; + island.Add(contact); - // Has the other body already been added to the island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - // Add the other body to the island. - other->m_flags |= b2Body::e_islandFlag; + // Has the other body already been added to the island? + if (other->m_flags & b2Body::e_islandFlag) + { + continue; + } + + // Add the other body to the island. + other->m_flags |= b2Body::e_islandFlag; - if (other->m_type != b2_staticBody) - { - other->SetAwake(true); - } + if (other->m_type != b2_staticBody) + { + other->SetAwake(true); + } - island.Add(other); - } - } - } + island.Add(other); + } + } + } - b2TimeStep subStep; - subStep.dt = (1.0f - minAlpha) * step.dt; - subStep.inv_dt = 1.0f / subStep.dt; - subStep.dtRatio = 1.0f; - subStep.positionIterations = 20; - subStep.velocityIterations = step.velocityIterations; - subStep.warmStarting = false; - island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); + b2TimeStep subStep; + subStep.dt = (1.0f - minAlpha) * step.dt; + subStep.inv_dt = 1.0f / subStep.dt; + subStep.dtRatio = 1.0f; + subStep.positionIterations = 20; + subStep.velocityIterations = step.velocityIterations; + subStep.warmStarting = false; + island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); - // Reset island flags and synchronize broad-phase proxies. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - b2Body* body = island.m_bodies[i]; - body->m_flags &= ~b2Body::e_islandFlag; + // Reset island flags and synchronize broad-phase proxies. + for (int32 i = 0; i < island.m_bodyCount; ++i) + { + b2Body* body = island.m_bodies[i]; + body->m_flags &= ~b2Body::e_islandFlag; - if (body->m_type != b2_dynamicBody) - { - continue; - } + if (body->m_type != b2_dynamicBody) + { + continue; + } - body->SynchronizeFixtures(); + body->SynchronizeFixtures(); - // Invalidate all contact TOIs on this displaced body. - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - } + // Invalidate all contact TOIs on this displaced body. + for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) + { + ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); + } + } - // Commit fixture proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_contactManager.FindNewContacts(); + // Commit fixture proxy movements to the broad-phase so that new contacts are created. + // Also, some contacts can be destroyed. + m_contactManager.FindNewContacts(); - if (m_subStepping) - { - m_stepComplete = false; - break; - } - } + if (m_subStepping) + { + m_stepComplete = false; + break; + } + } } void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) { - b2Timer stepTimer; + b2Timer stepTimer; - // If new fixtures were added, we need to find the new contacts. - if (m_flags & e_newFixture) - { - m_contactManager.FindNewContacts(); - m_flags &= ~e_newFixture; - } + // If new fixtures were added, we need to find the new contacts. + if (m_flags & e_newFixture) + { + m_contactManager.FindNewContacts(); + m_flags &= ~e_newFixture; + } - m_flags |= e_locked; + m_flags |= e_locked; - b2TimeStep step; - step.dt = dt; - step.velocityIterations = velocityIterations; - step.positionIterations = positionIterations; - if (dt > 0.0f) - { - step.inv_dt = 1.0f / dt; - } - else - { - step.inv_dt = 0.0f; - } + b2TimeStep step; + step.dt = dt; + step.velocityIterations = velocityIterations; + step.positionIterations = positionIterations; + if (dt > 0.0f) + { + step.inv_dt = 1.0f / dt; + } + else + { + step.inv_dt = 0.0f; + } - step.dtRatio = m_inv_dt0 * dt; + step.dtRatio = m_inv_dt0 * dt; - step.warmStarting = m_warmStarting; - - // Update contacts. This is where some contacts are destroyed. - { - b2Timer timer; - m_contactManager.Collide(); - m_profile.collide = timer.GetMilliseconds(); - } + step.warmStarting = m_warmStarting; + + // Update contacts. This is where some contacts are destroyed. + { + b2Timer timer; + m_contactManager.Collide(); + m_profile.collide = timer.GetMilliseconds(); + } - // Integrate velocities, solve velocity constraints, and integrate positions. - if (m_stepComplete && step.dt > 0.0f) - { - b2Timer timer; - Solve(step); - m_profile.solve = timer.GetMilliseconds(); - } + // Integrate velocities, solve velocity constraints, and integrate positions. + if (m_stepComplete && step.dt > 0.0f) + { + b2Timer timer; + Solve(step); + m_profile.solve = timer.GetMilliseconds(); + } - // Handle TOI events. - if (m_continuousPhysics && step.dt > 0.0f) - { - b2Timer timer; - SolveTOI(step); - m_profile.solveTOI = timer.GetMilliseconds(); - } + // Handle TOI events. + if (m_continuousPhysics && step.dt > 0.0f) + { + b2Timer timer; + SolveTOI(step); + m_profile.solveTOI = timer.GetMilliseconds(); + } - if (step.dt > 0.0f) - { - m_inv_dt0 = step.inv_dt; - } + if (step.dt > 0.0f) + { + m_inv_dt0 = step.inv_dt; + } - if (m_flags & e_clearForces) - { - ClearForces(); - } + if (m_flags & e_clearForces) + { + ClearForces(); + } - m_flags &= ~e_locked; + m_flags &= ~e_locked; - m_profile.step = stepTimer.GetMilliseconds(); + m_profile.step = stepTimer.GetMilliseconds(); } void b2World::ClearForces() { - for (b2Body* body = m_bodyList; body; body = body->GetNext()) - { - body->m_force.SetZero(); - body->m_torque = 0.0f; - } + for (b2Body* body = m_bodyList; body; body = body->GetNext()) + { + body->m_force.SetZero(); + body->m_torque = 0.0f; + } } struct b2WorldQueryWrapper { - bool QueryCallback(int32 proxyId) - { - b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); - return callback->ReportFixture(proxy->fixture); - } + bool QueryCallback(int32 proxyId) + { + b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); + return callback->ReportFixture(proxy->fixture); + } - const b2BroadPhase* broadPhase; - b2QueryCallback* callback; + const b2BroadPhase* broadPhase; + b2QueryCallback* callback; }; void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const { - b2WorldQueryWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - m_contactManager.m_broadPhase.Query(&wrapper, aabb); + b2WorldQueryWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + m_contactManager.m_broadPhase.Query(&wrapper, aabb); } struct b2WorldRayCastWrapper { - float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - void* userData = broadPhase->GetUserData(proxyId); - b2FixtureProxy* proxy = (b2FixtureProxy*)userData; - b2Fixture* fixture = proxy->fixture; - int32 index = proxy->childIndex; - b2RayCastOutput output; - bool hit = fixture->RayCast(&output, input, index); + float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + void* userData = broadPhase->GetUserData(proxyId); + b2FixtureProxy* proxy = (b2FixtureProxy*)userData; + b2Fixture* fixture = proxy->fixture; + int32 index = proxy->childIndex; + b2RayCastOutput output; + bool hit = fixture->RayCast(&output, input, index); - if (hit) - { - float32 fraction = output.fraction; - b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; - return callback->ReportFixture(fixture, point, output.normal, fraction); - } + if (hit) + { + float32 fraction = output.fraction; + b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; + return callback->ReportFixture(fixture, point, output.normal, fraction); + } - return input.maxFraction; - } + return input.maxFraction; + } - const b2BroadPhase* broadPhase; - b2RayCastCallback* callback; + const b2BroadPhase* broadPhase; + b2RayCastCallback* callback; }; void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const { - b2WorldRayCastWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - b2RayCastInput input; - input.maxFraction = 1.0f; - input.p1 = point1; - input.p2 = point2; - m_contactManager.m_broadPhase.RayCast(&wrapper, input); + b2WorldRayCastWrapper wrapper; + wrapper.broadPhase = &m_contactManager.m_broadPhase; + wrapper.callback = callback; + b2RayCastInput input; + input.maxFraction = 1.0f; + input.p1 = point1; + input.p2 = point2; + m_contactManager.m_broadPhase.RayCast(&wrapper, input); } void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) { - switch (fixture->GetType()) - { - case b2Shape::e_circle: - { - b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); + switch (fixture->GetType()) + { + case b2Shape::e_circle: + { + b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); - b2Vec2 center = b2Mul(xf, circle->m_p); - float32 radius = circle->m_radius; - b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); + b2Vec2 center = b2Mul(xf, circle->m_p); + float32 radius = circle->m_radius; + b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); - m_debugDraw->DrawSolidCircle(center, radius, axis, color); - } - break; + m_debugDraw->DrawSolidCircle(center, radius, axis, color); + } + break; - case b2Shape::e_edge: - { - b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); - b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); - b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); - m_debugDraw->DrawSegment(v1, v2, color); - } - break; + case b2Shape::e_edge: + { + b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); + b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); + b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); + m_debugDraw->DrawSegment(v1, v2, color); + } + break; - case b2Shape::e_chain: - { - b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); - int32 count = chain->m_count; - const b2Vec2* vertices = chain->m_vertices; + case b2Shape::e_chain: + { + b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); + int32 count = chain->m_count; + const b2Vec2* vertices = chain->m_vertices; - b2Vec2 v1 = b2Mul(xf, vertices[0]); - for (int32 i = 1; i < count; ++i) - { - b2Vec2 v2 = b2Mul(xf, vertices[i]); - m_debugDraw->DrawSegment(v1, v2, color); - m_debugDraw->DrawCircle(v1, 0.05f, color); - v1 = v2; - } - } - break; + b2Vec2 v1 = b2Mul(xf, vertices[0]); + for (int32 i = 1; i < count; ++i) + { + b2Vec2 v2 = b2Mul(xf, vertices[i]); + m_debugDraw->DrawSegment(v1, v2, color); + m_debugDraw->DrawCircle(v1, 0.05f, color); + v1 = v2; + } + } + break; - case b2Shape::e_polygon: - { - b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); - int32 vertexCount = poly->m_vertexCount; - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; + case b2Shape::e_polygon: + { + b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); + int32 vertexCount = poly->m_count; + b2Assert(vertexCount <= b2_maxPolygonVertices); + b2Vec2 vertices[b2_maxPolygonVertices]; - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, poly->m_vertices[i]); - } + for (int32 i = 0; i < vertexCount; ++i) + { + vertices[i] = b2Mul(xf, poly->m_vertices[i]); + } - m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); - } - break; + m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); + } + break; default: break; - } + } } void b2World::DrawJoint(b2Joint* joint) { - b2Body* bodyA = joint->GetBodyA(); - b2Body* bodyB = joint->GetBodyB(); - const b2Transform& xf1 = bodyA->GetTransform(); - const b2Transform& xf2 = bodyB->GetTransform(); - b2Vec2 x1 = xf1.p; - b2Vec2 x2 = xf2.p; - b2Vec2 p1 = joint->GetAnchorA(); - b2Vec2 p2 = joint->GetAnchorB(); + b2Body* bodyA = joint->GetBodyA(); + b2Body* bodyB = joint->GetBodyB(); + const b2Transform& xf1 = bodyA->GetTransform(); + const b2Transform& xf2 = bodyB->GetTransform(); + b2Vec2 x1 = xf1.p; + b2Vec2 x2 = xf2.p; + b2Vec2 p1 = joint->GetAnchorA(); + b2Vec2 p2 = joint->GetAnchorB(); - b2Color color(0.5f, 0.8f, 0.8f); + b2Color color(0.5f, 0.8f, 0.8f); - switch (joint->GetType()) - { - case e_distanceJoint: - m_debugDraw->DrawSegment(p1, p2, color); - break; + switch (joint->GetType()) + { + case e_distanceJoint: + m_debugDraw->DrawSegment(p1, p2, color); + break; - case e_pulleyJoint: - { - b2PulleyJoint* pulley = (b2PulleyJoint*)joint; - b2Vec2 s1 = pulley->GetGroundAnchorA(); - b2Vec2 s2 = pulley->GetGroundAnchorB(); - m_debugDraw->DrawSegment(s1, p1, color); - m_debugDraw->DrawSegment(s2, p2, color); - m_debugDraw->DrawSegment(s1, s2, color); - } - break; + case e_pulleyJoint: + { + b2PulleyJoint* pulley = (b2PulleyJoint*)joint; + b2Vec2 s1 = pulley->GetGroundAnchorA(); + b2Vec2 s2 = pulley->GetGroundAnchorB(); + m_debugDraw->DrawSegment(s1, p1, color); + m_debugDraw->DrawSegment(s2, p2, color); + m_debugDraw->DrawSegment(s1, s2, color); + } + break; - case e_mouseJoint: - // don't draw this - break; + case e_mouseJoint: + // don't draw this + break; - default: - m_debugDraw->DrawSegment(x1, p1, color); - m_debugDraw->DrawSegment(p1, p2, color); - m_debugDraw->DrawSegment(x2, p2, color); - } + default: + m_debugDraw->DrawSegment(x1, p1, color); + m_debugDraw->DrawSegment(p1, p2, color); + m_debugDraw->DrawSegment(x2, p2, color); + } } void b2World::DrawDebugData() { - if (m_debugDraw == NULL) - { - return; - } + if (m_debugDraw == NULL) + { + return; + } - uint32 flags = m_debugDraw->GetFlags(); + uint32 flags = m_debugDraw->GetFlags(); - if (flags & b2Draw::e_shapeBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2Transform& xf = b->GetTransform(); - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - if (b->IsActive() == false) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); - } - else if (b->GetType() == b2_staticBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); - } - else if (b->GetType() == b2_kinematicBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); - } - else if (b->IsAwake() == false) - { - DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); - } - else - { - DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); - } - } - } - } + if (flags & b2Draw::e_shapeBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + const b2Transform& xf = b->GetTransform(); + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + if (b->IsActive() == false) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); + } + else if (b->GetType() == b2_staticBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); + } + else if (b->GetType() == b2_kinematicBody) + { + DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); + } + else if (b->IsAwake() == false) + { + DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); + } + else + { + DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); + } + } + } + } - if (flags & b2Draw::e_jointBit) - { - for (b2Joint* j = m_jointList; j; j = j->GetNext()) - { - DrawJoint(j); - } - } + if (flags & b2Draw::e_jointBit) + { + for (b2Joint* j = m_jointList; j; j = j->GetNext()) + { + DrawJoint(j); + } + } - if (flags & b2Draw::e_pairBit) - { - b2Color color(0.3f, 0.9f, 0.9f); - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) - { - //b2Fixture* fixtureA = c->GetFixtureA(); - //b2Fixture* fixtureB = c->GetFixtureB(); + if (flags & b2Draw::e_pairBit) + { + b2Color color(0.3f, 0.9f, 0.9f); + for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) + { + //b2Fixture* fixtureA = c->GetFixtureA(); + //b2Fixture* fixtureB = c->GetFixtureB(); - //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); - //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); + //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); + //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); - //m_debugDraw->DrawSegment(cA, cB, color); - } - } + //m_debugDraw->DrawSegment(cA, cB, color); + } + } - if (flags & b2Draw::e_aabbBit) - { - b2Color color(0.9f, 0.3f, 0.9f); - b2BroadPhase* bp = &m_contactManager.m_broadPhase; + if (flags & b2Draw::e_aabbBit) + { + b2Color color(0.9f, 0.3f, 0.9f); + b2BroadPhase* bp = &m_contactManager.m_broadPhase; - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - if (b->IsActive() == false) - { - continue; - } + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + if (b->IsActive() == false) + { + continue; + } - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - for (int32 i = 0; i < f->m_proxyCount; ++i) - { - b2FixtureProxy* proxy = f->m_proxies + i; - b2AABB aabb = bp->GetFatAABB(proxy->proxyId); - b2Vec2 vs[4]; - vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); - vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); - vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); - vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); + for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) + { + for (int32 i = 0; i < f->m_proxyCount; ++i) + { + b2FixtureProxy* proxy = f->m_proxies + i; + b2AABB aabb = bp->GetFatAABB(proxy->proxyId); + b2Vec2 vs[4]; + vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); + vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); + vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); + vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); - m_debugDraw->DrawPolygon(vs, 4, color); - } - } - } - } + m_debugDraw->DrawPolygon(vs, 4, color); + } + } + } + } - if (flags & b2Draw::e_centerOfMassBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - b2Transform xf = b->GetTransform(); - xf.p = b->GetWorldCenter(); - m_debugDraw->DrawTransform(xf); - } - } + if (flags & b2Draw::e_centerOfMassBit) + { + for (b2Body* b = m_bodyList; b; b = b->GetNext()) + { + b2Transform xf = b->GetTransform(); + xf.p = b->GetWorldCenter(); + m_debugDraw->DrawTransform(xf); + } + } } int32 b2World::GetProxyCount() const { - return m_contactManager.m_broadPhase.GetProxyCount(); + return m_contactManager.m_broadPhase.GetProxyCount(); } int32 b2World::GetTreeHeight() const { - return m_contactManager.m_broadPhase.GetTreeHeight(); + return m_contactManager.m_broadPhase.GetTreeHeight(); } int32 b2World::GetTreeBalance() const { - return m_contactManager.m_broadPhase.GetTreeBalance(); + return m_contactManager.m_broadPhase.GetTreeBalance(); } float32 b2World::GetTreeQuality() const { - return m_contactManager.m_broadPhase.GetTreeQuality(); + return m_contactManager.m_broadPhase.GetTreeQuality(); +} + +void b2World::ShiftOrigin(const b2Vec2& newOrigin) +{ + b2Assert((m_flags & e_locked) == 0); + if ((m_flags & e_locked) == e_locked) + { + return; + } + + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_xf.p -= newOrigin; + b->m_sweep.c0 -= newOrigin; + b->m_sweep.c -= newOrigin; + } + + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->ShiftOrigin(newOrigin); + } + + m_contactManager.m_broadPhase.ShiftOrigin(newOrigin); } void b2World::Dump() { - if ((m_flags & e_locked) == e_locked) - { - return; - } + if ((m_flags & e_locked) == e_locked) + { + return; + } - b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); - b2Log("m_world->SetGravity(g);\n"); + b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); + b2Log("m_world->SetGravity(g);\n"); - b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); - b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); - int32 i = 0; - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_islandIndex = i; - b->Dump(); - ++i; - } + b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); + b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); + int32 i = 0; + for (b2Body* b = m_bodyList; b; b = b->m_next) + { + b->m_islandIndex = i; + b->Dump(); + ++i; + } - i = 0; - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_index = i; - ++i; - } + i = 0; + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + j->m_index = i; + ++i; + } - // First pass on joints, skip gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type == e_gearJoint) - { - continue; - } + // First pass on joints, skip gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type == e_gearJoint) + { + continue; + } - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } - // Second pass on joints, only gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type != e_gearJoint) - { - continue; - } + // Second pass on joints, only gear joints. + for (b2Joint* j = m_jointList; j; j = j->m_next) + { + if (j->m_type != e_gearJoint) + { + continue; + } - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } + b2Log("{\n"); + j->Dump(); + b2Log("}\n"); + } - b2Log("b2Free(joints);\n"); - b2Log("b2Free(bodies);\n"); - b2Log("joints = NULL;\n"); - b2Log("bodies = NULL;\n"); + b2Log("b2Free(joints);\n"); + b2Log("b2Free(bodies);\n"); + b2Log("joints = NULL;\n"); + b2Log("bodies = NULL;\n"); } diff --git a/external/Box2D/Dynamics/b2World.h b/external/Box2D/Dynamics/b2World.h index f207930511..4f94f6efe4 100644 --- a/external/Box2D/Dynamics/b2World.h +++ b/external/Box2D/Dynamics/b2World.h @@ -41,309 +41,314 @@ class b2Joint; class b2World { public: - /// Construct a world object. - /// @param gravity the world gravity vector. - b2World(const b2Vec2& gravity); + /// Construct a world object. + /// @param gravity the world gravity vector. + b2World(const b2Vec2& gravity); - /// Destruct the world. All physics entities are destroyed and all heap memory is released. - ~b2World(); + /// Destruct the world. All physics entities are destroyed and all heap memory is released. + ~b2World(); - /// Register a destruction listener. The listener is owned by you and must - /// remain in scope. - void SetDestructionListener(b2DestructionListener* listener); + /// Register a destruction listener. The listener is owned by you and must + /// remain in scope. + void SetDestructionListener(b2DestructionListener* listener); - /// Register a contact filter to provide specific control over collision. - /// Otherwise the default filter is used (b2_defaultFilter). The listener is - /// owned by you and must remain in scope. - void SetContactFilter(b2ContactFilter* filter); + /// Register a contact filter to provide specific control over collision. + /// Otherwise the default filter is used (b2_defaultFilter). The listener is + /// owned by you and must remain in scope. + void SetContactFilter(b2ContactFilter* filter); - /// Register a contact event listener. The listener is owned by you and must - /// remain in scope. - void SetContactListener(b2ContactListener* listener); + /// Register a contact event listener. The listener is owned by you and must + /// remain in scope. + void SetContactListener(b2ContactListener* listener); - /// Register a routine for debug drawing. The debug draw functions are called - /// inside with b2World::DrawDebugData method. The debug draw object is owned - /// by you and must remain in scope. - void SetDebugDraw(b2Draw* debugDraw); + /// Register a routine for debug drawing. The debug draw functions are called + /// inside with b2World::DrawDebugData method. The debug draw object is owned + /// by you and must remain in scope. + void SetDebugDraw(b2Draw* debugDraw); - /// Create a rigid body given a definition. No reference to the definition - /// is retained. - /// @warning This function is locked during callbacks. - b2Body* CreateBody(const b2BodyDef* def); + /// Create a rigid body given a definition. No reference to the definition + /// is retained. + /// @warning This function is locked during callbacks. + b2Body* CreateBody(const b2BodyDef* def); - /// Destroy a rigid body given a definition. No reference to the definition - /// is retained. This function is locked during callbacks. - /// @warning This automatically deletes all associated shapes and joints. - /// @warning This function is locked during callbacks. - void DestroyBody(b2Body* body); + /// Destroy a rigid body given a definition. No reference to the definition + /// is retained. This function is locked during callbacks. + /// @warning This automatically deletes all associated shapes and joints. + /// @warning This function is locked during callbacks. + void DestroyBody(b2Body* body); - /// Create a joint to constrain bodies together. No reference to the definition - /// is retained. This may cause the connected bodies to cease colliding. - /// @warning This function is locked during callbacks. - b2Joint* CreateJoint(const b2JointDef* def); + /// Create a joint to constrain bodies together. No reference to the definition + /// is retained. This may cause the connected bodies to cease colliding. + /// @warning This function is locked during callbacks. + b2Joint* CreateJoint(const b2JointDef* def); - /// Destroy a joint. This may cause the connected bodies to begin colliding. - /// @warning This function is locked during callbacks. - void DestroyJoint(b2Joint* joint); + /// Destroy a joint. This may cause the connected bodies to begin colliding. + /// @warning This function is locked during callbacks. + void DestroyJoint(b2Joint* joint); - /// Take a time step. This performs collision detection, integration, - /// and constraint solution. - /// @param timeStep the amount of time to simulate, this should not vary. - /// @param velocityIterations for the velocity constraint solver. - /// @param positionIterations for the position constraint solver. - void Step( float32 timeStep, - int32 velocityIterations, - int32 positionIterations); + /// Take a time step. This performs collision detection, integration, + /// and constraint solution. + /// @param timeStep the amount of time to simulate, this should not vary. + /// @param velocityIterations for the velocity constraint solver. + /// @param positionIterations for the position constraint solver. + void Step( float32 timeStep, + int32 velocityIterations, + int32 positionIterations); - /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically - /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. - /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain - /// a fixed sized time step under a variable frame-rate. - /// When you perform sub-stepping you will disable auto clearing of forces and instead call - /// ClearForces after all sub-steps are complete in one pass of your game loop. - /// @see SetAutoClearForces - void ClearForces(); + /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically + /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. + /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain + /// a fixed sized time step under a variable frame-rate. + /// When you perform sub-stepping you will disable auto clearing of forces and instead call + /// ClearForces after all sub-steps are complete in one pass of your game loop. + /// @see SetAutoClearForces + void ClearForces(); - /// Call this to draw shapes and other debug draw data. - void DrawDebugData(); + /// Call this to draw shapes and other debug draw data. This is intentionally non-const. + void DrawDebugData(); - /// Query the world for all fixtures that potentially overlap the - /// provided AABB. - /// @param callback a user implemented callback class. - /// @param aabb the query box. - void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; + /// Query the world for all fixtures that potentially overlap the + /// provided AABB. + /// @param callback a user implemented callback class. + /// @param aabb the query box. + void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; - /// Ray-cast the world for all fixtures in the path of the ray. Your callback - /// controls whether you get the closest point, any point, or n-points. - /// The ray-cast ignores shapes that contain the starting point. - /// @param callback a user implemented callback class. - /// @param point1 the ray starting point - /// @param point2 the ray ending point - void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; + /// Ray-cast the world for all fixtures in the path of the ray. Your callback + /// controls whether you get the closest point, any point, or n-points. + /// The ray-cast ignores shapes that contain the starting point. + /// @param callback a user implemented callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point + void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; - /// Get the world body list. With the returned body, use b2Body::GetNext to get - /// the next body in the world list. A NULL body indicates the end of the list. - /// @return the head of the world body list. - b2Body* GetBodyList(); - const b2Body* GetBodyList() const; + /// Get the world body list. With the returned body, use b2Body::GetNext to get + /// the next body in the world list. A NULL body indicates the end of the list. + /// @return the head of the world body list. + b2Body* GetBodyList(); + const b2Body* GetBodyList() const; - /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get - /// the next joint in the world list. A NULL joint indicates the end of the list. - /// @return the head of the world joint list. - b2Joint* GetJointList(); - const b2Joint* GetJointList() const; + /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get + /// the next joint in the world list. A NULL joint indicates the end of the list. + /// @return the head of the world joint list. + b2Joint* GetJointList(); + const b2Joint* GetJointList() const; - /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get - /// the next contact in the world list. A NULL contact indicates the end of the list. - /// @return the head of the world contact list. - /// @warning contacts are created and destroyed in the middle of a time step. - /// Use b2ContactListener to avoid missing contacts. - b2Contact* GetContactList(); - const b2Contact* GetContactList() const; + /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get + /// the next contact in the world list. A NULL contact indicates the end of the list. + /// @return the head of the world contact list. + /// @warning contacts are created and destroyed in the middle of a time step. + /// Use b2ContactListener to avoid missing contacts. + b2Contact* GetContactList(); + const b2Contact* GetContactList() const; - /// Enable/disable sleep. - void SetAllowSleeping(bool flag); - bool GetAllowSleeping() const { return m_allowSleep; } + /// Enable/disable sleep. + void SetAllowSleeping(bool flag); + bool GetAllowSleeping() const { return m_allowSleep; } - /// Enable/disable warm starting. For testing. - void SetWarmStarting(bool flag) { m_warmStarting = flag; } - bool GetWarmStarting() const { return m_warmStarting; } + /// Enable/disable warm starting. For testing. + void SetWarmStarting(bool flag) { m_warmStarting = flag; } + bool GetWarmStarting() const { return m_warmStarting; } - /// Enable/disable continuous physics. For testing. - void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } - bool GetContinuousPhysics() const { return m_continuousPhysics; } + /// Enable/disable continuous physics. For testing. + void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } + bool GetContinuousPhysics() const { return m_continuousPhysics; } - /// Enable/disable single stepped continuous physics. For testing. - void SetSubStepping(bool flag) { m_subStepping = flag; } - bool GetSubStepping() const { return m_subStepping; } + /// Enable/disable single stepped continuous physics. For testing. + void SetSubStepping(bool flag) { m_subStepping = flag; } + bool GetSubStepping() const { return m_subStepping; } - /// Get the number of broad-phase proxies. - int32 GetProxyCount() const; + /// Get the number of broad-phase proxies. + int32 GetProxyCount() const; - /// Get the number of bodies. - int32 GetBodyCount() const; + /// Get the number of bodies. + int32 GetBodyCount() const; - /// Get the number of joints. - int32 GetJointCount() const; + /// Get the number of joints. + int32 GetJointCount() const; - /// Get the number of contacts (each may have 0 or more contact points). - int32 GetContactCount() const; + /// Get the number of contacts (each may have 0 or more contact points). + int32 GetContactCount() const; - /// Get the height of the dynamic tree. - int32 GetTreeHeight() const; + /// Get the height of the dynamic tree. + int32 GetTreeHeight() const; - /// Get the balance of the dynamic tree. - int32 GetTreeBalance() const; + /// Get the balance of the dynamic tree. + int32 GetTreeBalance() const; - /// Get the quality metric of the dynamic tree. The smaller the better. - /// The minimum is 1. - float32 GetTreeQuality() const; + /// Get the quality metric of the dynamic tree. The smaller the better. + /// The minimum is 1. + float32 GetTreeQuality() const; - /// Change the global gravity vector. - void SetGravity(const b2Vec2& gravity); - - /// Get the global gravity vector. - b2Vec2 GetGravity() const; + /// Change the global gravity vector. + void SetGravity(const b2Vec2& gravity); + + /// Get the global gravity vector. + b2Vec2 GetGravity() const; - /// Is the world locked (in the middle of a time step). - bool IsLocked() const; + /// Is the world locked (in the middle of a time step). + bool IsLocked() const; - /// Set flag to control automatic clearing of forces after each time step. - void SetAutoClearForces(bool flag); + /// Set flag to control automatic clearing of forces after each time step. + void SetAutoClearForces(bool flag); - /// Get the flag that controls automatic clearing of forces after each time step. - bool GetAutoClearForces() const; + /// Get the flag that controls automatic clearing of forces after each time step. + bool GetAutoClearForces() const; - /// Get the contact manager for testing. - const b2ContactManager& GetContactManager() const; + /// Shift the world origin. Useful for large worlds. + /// The body shift formula is: position -= newOrigin + /// @param newOrigin the new origin with respect to the old origin + void ShiftOrigin(const b2Vec2& newOrigin); - /// Get the current profile. - const b2Profile& GetProfile() const; + /// Get the contact manager for testing. + const b2ContactManager& GetContactManager() const; - /// Dump the world into the log file. - /// @warning this should be called outside of a time step. - void Dump(); + /// Get the current profile. + const b2Profile& GetProfile() const; + + /// Dump the world into the log file. + /// @warning this should be called outside of a time step. + void Dump(); private: - // m_flags - enum - { - e_newFixture = 0x0001, - e_locked = 0x0002, - e_clearForces = 0x0004 - }; + // m_flags + enum + { + e_newFixture = 0x0001, + e_locked = 0x0002, + e_clearForces = 0x0004 + }; - friend class b2Body; - friend class b2Fixture; - friend class b2ContactManager; - friend class b2Controller; + friend class b2Body; + friend class b2Fixture; + friend class b2ContactManager; + friend class b2Controller; - void Solve(const b2TimeStep& step); - void SolveTOI(const b2TimeStep& step); + void Solve(const b2TimeStep& step); + void SolveTOI(const b2TimeStep& step); - void DrawJoint(b2Joint* joint); - void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); + void DrawJoint(b2Joint* joint); + void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); - b2BlockAllocator m_blockAllocator; - b2StackAllocator m_stackAllocator; + b2BlockAllocator m_blockAllocator; + b2StackAllocator m_stackAllocator; - int32 m_flags; + int32 m_flags; - b2ContactManager m_contactManager; + b2ContactManager m_contactManager; - b2Body* m_bodyList; - b2Joint* m_jointList; + b2Body* m_bodyList; + b2Joint* m_jointList; - int32 m_bodyCount; - int32 m_jointCount; + int32 m_bodyCount; + int32 m_jointCount; - b2Vec2 m_gravity; - bool m_allowSleep; + b2Vec2 m_gravity; + bool m_allowSleep; - b2DestructionListener* m_destructionListener; - b2Draw* m_debugDraw; + b2DestructionListener* m_destructionListener; + b2Draw* m_debugDraw; - // This is used to compute the time step ratio to - // support a variable time step. - float32 m_inv_dt0; + // This is used to compute the time step ratio to + // support a variable time step. + float32 m_inv_dt0; - // These are for debugging the solver. - bool m_warmStarting; - bool m_continuousPhysics; - bool m_subStepping; + // These are for debugging the solver. + bool m_warmStarting; + bool m_continuousPhysics; + bool m_subStepping; - bool m_stepComplete; + bool m_stepComplete; - b2Profile m_profile; + b2Profile m_profile; }; inline b2Body* b2World::GetBodyList() { - return m_bodyList; + return m_bodyList; } inline const b2Body* b2World::GetBodyList() const { - return m_bodyList; + return m_bodyList; } inline b2Joint* b2World::GetJointList() { - return m_jointList; + return m_jointList; } inline const b2Joint* b2World::GetJointList() const { - return m_jointList; + return m_jointList; } inline b2Contact* b2World::GetContactList() { - return m_contactManager.m_contactList; + return m_contactManager.m_contactList; } inline const b2Contact* b2World::GetContactList() const { - return m_contactManager.m_contactList; + return m_contactManager.m_contactList; } inline int32 b2World::GetBodyCount() const { - return m_bodyCount; + return m_bodyCount; } inline int32 b2World::GetJointCount() const { - return m_jointCount; + return m_jointCount; } inline int32 b2World::GetContactCount() const { - return m_contactManager.m_contactCount; + return m_contactManager.m_contactCount; } inline void b2World::SetGravity(const b2Vec2& gravity) { - m_gravity = gravity; + m_gravity = gravity; } inline b2Vec2 b2World::GetGravity() const { - return m_gravity; + return m_gravity; } inline bool b2World::IsLocked() const { - return (m_flags & e_locked) == e_locked; + return (m_flags & e_locked) == e_locked; } inline void b2World::SetAutoClearForces(bool flag) { - if (flag) - { - m_flags |= e_clearForces; - } - else - { - m_flags &= ~e_clearForces; - } + if (flag) + { + m_flags |= e_clearForces; + } + else + { + m_flags &= ~e_clearForces; + } } /// Get the flag that controls automatic clearing of forces after each time step. inline bool b2World::GetAutoClearForces() const { - return (m_flags & e_clearForces) == e_clearForces; + return (m_flags & e_clearForces) == e_clearForces; } inline const b2ContactManager& b2World::GetContactManager() const { - return m_contactManager; + return m_contactManager; } inline const b2Profile& b2World::GetProfile() const { - return m_profile; + return m_profile; } #endif diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.cpp b/external/Box2D/Dynamics/b2WorldCallbacks.cpp index 48ad0cc46a..0f4b9c53c0 100644 --- a/external/Box2D/Dynamics/b2WorldCallbacks.cpp +++ b/external/Box2D/Dynamics/b2WorldCallbacks.cpp @@ -23,14 +23,14 @@ // If you implement your own collision filter you may want to build from this implementation. bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) { - const b2Filter& filterA = fixtureA->GetFilterData(); - const b2Filter& filterB = fixtureB->GetFilterData(); + const b2Filter& filterA = fixtureA->GetFilterData(); + const b2Filter& filterB = fixtureB->GetFilterData(); - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) - { - return filterA.groupIndex > 0; - } + if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) + { + return filterA.groupIndex > 0; + } - bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; - return collide; + bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; + return collide; } diff --git a/external/Box2D/Dynamics/b2WorldCallbacks.h b/external/Box2D/Dynamics/b2WorldCallbacks.h index 86c04e3e32..82ffc02295 100644 --- a/external/Box2D/Dynamics/b2WorldCallbacks.h +++ b/external/Box2D/Dynamics/b2WorldCallbacks.h @@ -36,15 +36,15 @@ struct b2Manifold; class b2DestructionListener { public: - virtual ~b2DestructionListener() {} + virtual ~b2DestructionListener() {} - /// Called when any joint is about to be destroyed due - /// to the destruction of one of its attached bodies. - virtual void SayGoodbye(b2Joint* joint) = 0; + /// Called when any joint is about to be destroyed due + /// to the destruction of one of its attached bodies. + virtual void SayGoodbye(b2Joint* joint) = 0; - /// Called when any fixture is about to be destroyed due - /// to the destruction of its parent body. - virtual void SayGoodbye(b2Fixture* fixture) = 0; + /// Called when any fixture is about to be destroyed due + /// to the destruction of its parent body. + virtual void SayGoodbye(b2Fixture* fixture) = 0; }; /// Implement this class to provide collision filtering. In other words, you can implement @@ -52,11 +52,11 @@ public: class b2ContactFilter { public: - virtual ~b2ContactFilter() {} + virtual ~b2ContactFilter() {} - /// Return true if contact calculations should be performed between these two shapes. - /// @warning for performance reasons this is only called when the AABBs begin to overlap. - virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); + /// Return true if contact calculations should be performed between these two shapes. + /// @warning for performance reasons this is only called when the AABBs begin to overlap. + virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); }; /// Contact impulses for reporting. Impulses are used instead of forces because @@ -64,9 +64,9 @@ public: /// match up one-to-one with the contact points in b2Manifold. struct b2ContactImpulse { - float32 normalImpulses[b2_maxManifoldPoints]; - float32 tangentImpulses[b2_maxManifoldPoints]; - int32 count; + float32 normalImpulses[b2_maxManifoldPoints]; + float32 tangentImpulses[b2_maxManifoldPoints]; + int32 count; }; /// Implement this class to get contact information. You can use these results for @@ -81,41 +81,41 @@ struct b2ContactImpulse class b2ContactListener { public: - virtual ~b2ContactListener() {} + virtual ~b2ContactListener() {} - /// Called when two fixtures begin to touch. - virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } + /// Called when two fixtures begin to touch. + virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } - /// Called when two fixtures cease to touch. - virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } + /// Called when two fixtures cease to touch. + virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } - /// This is called after a contact is updated. This allows you to inspect a - /// contact before it goes to the solver. If you are careful, you can modify the - /// contact manifold (e.g. disable contact). - /// A copy of the old manifold is provided so that you can detect changes. - /// Note: this is called only for awake bodies. - /// Note: this is called even when the number of contact points is zero. - /// Note: this is not called for sensors. - /// Note: if you set the number of contact points to zero, you will not - /// get an EndContact callback. However, you may get a BeginContact callback - /// the next step. - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) - { - B2_NOT_USED(contact); - B2_NOT_USED(oldManifold); - } + /// This is called after a contact is updated. This allows you to inspect a + /// contact before it goes to the solver. If you are careful, you can modify the + /// contact manifold (e.g. disable contact). + /// A copy of the old manifold is provided so that you can detect changes. + /// Note: this is called only for awake bodies. + /// Note: this is called even when the number of contact points is zero. + /// Note: this is not called for sensors. + /// Note: if you set the number of contact points to zero, you will not + /// get an EndContact callback. However, you may get a BeginContact callback + /// the next step. + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + B2_NOT_USED(contact); + B2_NOT_USED(oldManifold); + } - /// This lets you inspect a contact after the solver is finished. This is useful - /// for inspecting impulses. - /// Note: the contact manifold does not include time of impact impulses, which can be - /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - /// in a separate data structure. - /// Note: this is only called for contacts that are touching, solid, and awake. - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } + /// This lets you inspect a contact after the solver is finished. This is useful + /// for inspecting impulses. + /// Note: the contact manifold does not include time of impact impulses, which can be + /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly + /// in a separate data structure. + /// Note: this is only called for contacts that are touching, solid, and awake. + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } }; /// Callback class for AABB queries. @@ -123,11 +123,11 @@ public: class b2QueryCallback { public: - virtual ~b2QueryCallback() {} + virtual ~b2QueryCallback() {} - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - virtual bool ReportFixture(b2Fixture* fixture) = 0; + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + virtual bool ReportFixture(b2Fixture* fixture) = 0; }; /// Callback class for ray casts. @@ -135,21 +135,21 @@ public: class b2RayCastCallback { public: - virtual ~b2RayCastCallback() {} + virtual ~b2RayCastCallback() {} - /// Called for each fixture found in the query. You control how the ray cast - /// proceeds by returning a float: - /// return -1: ignore this fixture and continue - /// return 0: terminate the ray cast - /// return fraction: clip the ray to this point - /// return 1: don't clip the ray and continue - /// @param fixture the fixture hit by the ray - /// @param point the point of initial intersection - /// @param normal the normal vector at the point of intersection - /// @return -1 to filter, 0 to terminate, fraction to clip the ray for - /// closest hit, 1 to continue - virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) = 0; + /// Called for each fixture found in the query. You control how the ray cast + /// proceeds by returning a float: + /// return -1: ignore this fixture and continue + /// return 0: terminate the ray cast + /// return fraction: clip the ray to this point + /// return 1: don't clip the ray and continue + /// @param fixture the fixture hit by the ray + /// @param point the point of initial intersection + /// @param normal the normal vector at the point of intersection + /// @return -1 to filter, 0 to terminate, fraction to clip the ray for + /// closest hit, 1 to continue + virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float32 fraction) = 0; }; #endif diff --git a/external/Box2D/Rope/b2Rope.cpp b/external/Box2D/Rope/b2Rope.cpp index 9bf671aec9..7af3a6cf2f 100644 --- a/external/Box2D/Rope/b2Rope.cpp +++ b/external/Box2D/Rope/b2Rope.cpp @@ -21,239 +21,239 @@ b2Rope::b2Rope() { - m_count = 0; - m_ps = NULL; - m_p0s = NULL; - m_vs = NULL; - m_ims = NULL; - m_Ls = NULL; - m_as = NULL; - m_gravity.SetZero(); - m_k2 = 1.0f; - m_k3 = 0.1f; + m_count = 0; + m_ps = NULL; + m_p0s = NULL; + m_vs = NULL; + m_ims = NULL; + m_Ls = NULL; + m_as = NULL; + m_gravity.SetZero(); + m_k2 = 1.0f; + m_k3 = 0.1f; } b2Rope::~b2Rope() { - b2Free(m_ps); - b2Free(m_p0s); - b2Free(m_vs); - b2Free(m_ims); - b2Free(m_Ls); - b2Free(m_as); + b2Free(m_ps); + b2Free(m_p0s); + b2Free(m_vs); + b2Free(m_ims); + b2Free(m_Ls); + b2Free(m_as); } void b2Rope::Initialize(const b2RopeDef* def) { - b2Assert(def->count >= 3); - m_count = def->count; - m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); + b2Assert(def->count >= 3); + m_count = def->count; + m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); + m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); - for (int32 i = 0; i < m_count; ++i) - { - m_ps[i] = def->vertices[i]; - m_p0s[i] = def->vertices[i]; - m_vs[i].SetZero(); + for (int32 i = 0; i < m_count; ++i) + { + m_ps[i] = def->vertices[i]; + m_p0s[i] = def->vertices[i]; + m_vs[i].SetZero(); - float32 m = def->masses[i]; - if (m > 0.0f) - { - m_ims[i] = 1.0f / m; - } - else - { - m_ims[i] = 0.0f; - } - } + float32 m = def->masses[i]; + if (m > 0.0f) + { + m_ims[i] = 1.0f / m; + } + else + { + m_ims[i] = 0.0f; + } + } - int32 count2 = m_count - 1; - int32 count3 = m_count - 2; - m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); - m_as = (float32*)b2Alloc(count3 * sizeof(float32)); + int32 count2 = m_count - 1; + int32 count3 = m_count - 2; + m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); + m_as = (float32*)b2Alloc(count3 * sizeof(float32)); - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i+1]; - m_Ls[i] = b2Distance(p1, p2); - } + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i+1]; + m_Ls[i] = b2Distance(p1, p2); + } - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); - m_as[i] = b2Atan2(a, b); - } + m_as[i] = b2Atan2(a, b); + } - m_gravity = def->gravity; - m_damping = def->damping; - m_k2 = def->k2; - m_k3 = def->k3; + m_gravity = def->gravity; + m_damping = def->damping; + m_k2 = def->k2; + m_k3 = def->k3; } void b2Rope::Step(float32 h, int32 iterations) { - if (h == 0.0) - { - return; - } + if (h == 0.0) + { + return; + } - float32 d = expf(- h * m_damping); + float32 d = expf(- h * m_damping); - for (int32 i = 0; i < m_count; ++i) - { - m_p0s[i] = m_ps[i]; - if (m_ims[i] > 0.0f) - { - m_vs[i] += h * m_gravity; - } - m_vs[i] *= d; - m_ps[i] += h * m_vs[i]; + for (int32 i = 0; i < m_count; ++i) + { + m_p0s[i] = m_ps[i]; + if (m_ims[i] > 0.0f) + { + m_vs[i] += h * m_gravity; + } + m_vs[i] *= d; + m_ps[i] += h * m_vs[i]; - } + } - for (int32 i = 0; i < iterations; ++i) - { - SolveC2(); - SolveC3(); - SolveC2(); - } + for (int32 i = 0; i < iterations; ++i) + { + SolveC2(); + SolveC3(); + SolveC2(); + } - float32 inv_h = 1.0f / h; - for (int32 i = 0; i < m_count; ++i) - { - m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); - } + float32 inv_h = 1.0f / h; + for (int32 i = 0; i < m_count; ++i) + { + m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); + } } void b2Rope::SolveC2() { - int32 count2 = m_count - 1; + int32 count2 = m_count - 1; - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; + for (int32 i = 0; i < count2; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 d = p2 - p1; - float32 L = d.Normalize(); + b2Vec2 d = p2 - p1; + float32 L = d.Normalize(); - float32 im1 = m_ims[i]; - float32 im2 = m_ims[i + 1]; + float32 im1 = m_ims[i]; + float32 im2 = m_ims[i + 1]; - if (im1 + im2 == 0.0f) - { - continue; - } + if (im1 + im2 == 0.0f) + { + continue; + } - float32 s1 = im1 / (im1 + im2); - float32 s2 = im2 / (im1 + im2); + float32 s1 = im1 / (im1 + im2); + float32 s2 = im2 / (im1 + im2); - p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; - p2 += m_k2 * s2 * (m_Ls[i] - L) * d; + p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; + p2 += m_k2 * s2 * (m_Ls[i] - L) * d; - m_ps[i] = p1; - m_ps[i + 1] = p2; - } + m_ps[i] = p1; + m_ps[i + 1] = p2; + } } void b2Rope::SetAngle(float32 angle) { - int32 count3 = m_count - 2; - for (int32 i = 0; i < count3; ++i) - { - m_as[i] = angle; - } + int32 count3 = m_count - 2; + for (int32 i = 0; i < count3; ++i) + { + m_as[i] = angle; + } } void b2Rope::SolveC3() { - int32 count3 = m_count - 2; + int32 count3 = m_count - 2; - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; + for (int32 i = 0; i < count3; ++i) + { + b2Vec2 p1 = m_ps[i]; + b2Vec2 p2 = m_ps[i + 1]; + b2Vec2 p3 = m_ps[i + 2]; - float32 m1 = m_ims[i]; - float32 m2 = m_ims[i + 1]; - float32 m3 = m_ims[i + 2]; + float32 m1 = m_ims[i]; + float32 m2 = m_ims[i + 1]; + float32 m3 = m_ims[i + 2]; - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; + b2Vec2 d1 = p2 - p1; + b2Vec2 d2 = p3 - p2; - float32 L1sqr = d1.LengthSquared(); - float32 L2sqr = d2.LengthSquared(); + float32 L1sqr = d1.LengthSquared(); + float32 L2sqr = d2.LengthSquared(); - if (L1sqr * L2sqr == 0.0f) - { - continue; - } + if (L1sqr * L2sqr == 0.0f) + { + continue; + } - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); + float32 a = b2Cross(d1, d2); + float32 b = b2Dot(d1, d2); - float32 angle = b2Atan2(a, b); + float32 angle = b2Atan2(a, b); - b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); - b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); + b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); + b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); - b2Vec2 J1 = -Jd1; - b2Vec2 J2 = Jd1 - Jd2; - b2Vec2 J3 = Jd2; + b2Vec2 J1 = -Jd1; + b2Vec2 J2 = Jd1 - Jd2; + b2Vec2 J3 = Jd2; - float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); - if (mass == 0.0f) - { - continue; - } + float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); + if (mass == 0.0f) + { + continue; + } - mass = 1.0f / mass; + mass = 1.0f / mass; - float32 C = angle - m_as[i]; + float32 C = angle - m_as[i]; - while (C > b2_pi) - { - angle -= 2 * b2_pi; - C = angle - m_as[i]; - } + while (C > b2_pi) + { + angle -= 2 * b2_pi; + C = angle - m_as[i]; + } - while (C < -b2_pi) - { - angle += 2.0f * b2_pi; - C = angle - m_as[i]; - } + while (C < -b2_pi) + { + angle += 2.0f * b2_pi; + C = angle - m_as[i]; + } - float32 impulse = - m_k3 * mass * C; + float32 impulse = - m_k3 * mass * C; - p1 += (m1 * impulse) * J1; - p2 += (m2 * impulse) * J2; - p3 += (m3 * impulse) * J3; + p1 += (m1 * impulse) * J1; + p2 += (m2 * impulse) * J2; + p3 += (m3 * impulse) * J3; - m_ps[i] = p1; - m_ps[i + 1] = p2; - m_ps[i + 2] = p3; - } + m_ps[i] = p1; + m_ps[i + 1] = p2; + m_ps[i + 2] = p3; + } } void b2Rope::Draw(b2Draw* draw) const { - b2Color c(0.4f, 0.5f, 0.7f); + b2Color c(0.4f, 0.5f, 0.7f); - for (int32 i = 0; i < m_count - 1; ++i) - { - draw->DrawSegment(m_ps[i], m_ps[i+1], c); - } + for (int32 i = 0; i < m_count - 1; ++i) + { + draw->DrawSegment(m_ps[i], m_ps[i+1], c); + } } diff --git a/external/Box2D/Rope/b2Rope.h b/external/Box2D/Rope/b2Rope.h index b981dfd6c5..246cf923f9 100644 --- a/external/Box2D/Rope/b2Rope.h +++ b/external/Box2D/Rope/b2Rope.h @@ -26,90 +26,90 @@ class b2Draw; /// struct b2RopeDef { - b2RopeDef() - { - vertices = NULL; - count = 0; - masses = NULL; - gravity.SetZero(); - damping = 0.1f; - k2 = 0.9f; - k3 = 0.1f; - } + b2RopeDef() + { + vertices = NULL; + count = 0; + masses = NULL; + gravity.SetZero(); + damping = 0.1f; + k2 = 0.9f; + k3 = 0.1f; + } - /// - b2Vec2* vertices; + /// + b2Vec2* vertices; - /// - int32 count; + /// + int32 count; - /// - float32* masses; + /// + float32* masses; - /// - b2Vec2 gravity; + /// + b2Vec2 gravity; - /// - float32 damping; + /// + float32 damping; - /// Stretching stiffness - float32 k2; + /// Stretching stiffness + float32 k2; - /// Bending stiffness. Values above 0.5 can make the simulation blow up. - float32 k3; + /// Bending stiffness. Values above 0.5 can make the simulation blow up. + float32 k3; }; /// class b2Rope { public: - b2Rope(); - ~b2Rope(); + b2Rope(); + ~b2Rope(); - /// - void Initialize(const b2RopeDef* def); + /// + void Initialize(const b2RopeDef* def); - /// - void Step(float32 timeStep, int32 iterations); + /// + void Step(float32 timeStep, int32 iterations); - /// - int32 GetVertexCount() const - { - return m_count; - } + /// + int32 GetVertexCount() const + { + return m_count; + } - /// - const b2Vec2* GetVertices() const - { - return m_ps; - } + /// + const b2Vec2* GetVertices() const + { + return m_ps; + } - /// - void Draw(b2Draw* draw) const; + /// + void Draw(b2Draw* draw) const; - /// - void SetAngle(float32 angle); + /// + void SetAngle(float32 angle); private: - void SolveC2(); - void SolveC3(); + void SolveC2(); + void SolveC3(); - int32 m_count; - b2Vec2* m_ps; - b2Vec2* m_p0s; - b2Vec2* m_vs; + int32 m_count; + b2Vec2* m_ps; + b2Vec2* m_p0s; + b2Vec2* m_vs; - float32* m_ims; + float32* m_ims; - float32* m_Ls; - float32* m_as; + float32* m_Ls; + float32* m_as; - b2Vec2 m_gravity; - float32 m_damping; + b2Vec2 m_gravity; + float32 m_damping; - float32 m_k2; - float32 m_k3; + float32 m_k2; + float32 m_k3; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp index cd2ee06547..be95c13f45 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp @@ -23,428 +23,438 @@ void DestructionListener::SayGoodbye(b2Joint* joint) { - if (test->m_mouseJoint == joint) - { - test->m_mouseJoint = NULL; - } - else - { - test->JointDestroyed(joint); - } + if (test->m_mouseJoint == joint) + { + test->m_mouseJoint = NULL; + } + else + { + test->JointDestroyed(joint); + } } Test::Test() { - b2Vec2 gravity; - gravity.Set(0.0f, -10.0f); - m_world = new b2World(gravity); - m_bomb = NULL; - m_textLine = 30; - m_mouseJoint = NULL; - m_pointCount = 0; + b2Vec2 gravity; + gravity.Set(0.0f, -10.0f); + m_world = new b2World(gravity); + m_bomb = NULL; + m_textLine = 30; + m_mouseJoint = NULL; + m_pointCount = 0; - m_destructionListener.test = this; - m_world->SetDestructionListener(&m_destructionListener); - m_world->SetContactListener(this); - m_world->SetDebugDraw(&m_debugDraw); - - m_bombSpawning = false; + m_destructionListener.test = this; + m_world->SetDestructionListener(&m_destructionListener); + m_world->SetContactListener(this); + m_world->SetDebugDraw(&m_debugDraw); + + m_bombSpawning = false; - m_stepCount = 0; + m_stepCount = 0; - b2BodyDef bodyDef; - m_groundBody = m_world->CreateBody(&bodyDef); + b2BodyDef bodyDef; + m_groundBody = m_world->CreateBody(&bodyDef); - memset(&m_maxProfile, 0, sizeof(b2Profile)); - memset(&m_totalProfile, 0, sizeof(b2Profile)); + memset(&m_maxProfile, 0, sizeof(b2Profile)); + memset(&m_totalProfile, 0, sizeof(b2Profile)); } Test::~Test() { - // By deleting the world, we delete the bomb, mouse joint, etc. - delete m_world; - m_world = NULL; + // By deleting the world, we delete the bomb, mouse joint, etc. + delete m_world; + m_world = NULL; } void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { - const b2Manifold* manifold = contact->GetManifold(); + const b2Manifold* manifold = contact->GetManifold(); - if (manifold->pointCount == 0) - { - return; - } + if (manifold->pointCount == 0) + { + return; + } - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; - b2GetPointStates(state1, state2, oldManifold, manifold); + b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; + b2GetPointStates(state1, state2, oldManifold, manifold); - b2WorldManifold worldManifold; - contact->GetWorldManifold(&worldManifold); + b2WorldManifold worldManifold; + contact->GetWorldManifold(&worldManifold); - for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) - { - auto cp = m_points + m_pointCount; - cp->fixtureA = fixtureA; - cp->fixtureB = fixtureB; - cp->position = worldManifold.points[i]; - cp->normal = worldManifold.normal; - cp->state = state2[i]; - ++m_pointCount; - } + for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) + { + ContactPoint* cp = m_points + m_pointCount; + cp->fixtureA = fixtureA; + cp->fixtureB = fixtureB; + cp->position = worldManifold.points[i]; + cp->normal = worldManifold.normal; + cp->state = state2[i]; + cp->normalImpulse = manifold->points[i].normalImpulse; + cp->tangentImpulse = manifold->points[i].tangentImpulse; + cp->separation = worldManifold.separations[i]; + ++m_pointCount; + } } -void Test::DrawTitle(int x, int y, const char *string) +void Test::DrawTitle(const char *string) { - m_debugDraw.DrawString(x, y, string); + m_debugDraw.DrawString(5, DRAW_STRING_NEW_LINE, string); + m_textLine = 2 * DRAW_STRING_NEW_LINE; } class QueryCallback : public b2QueryCallback { public: - QueryCallback(const b2Vec2& point) - { - m_point = point; - m_fixture = NULL; - } + QueryCallback(const b2Vec2& point) + { + m_point = point; + m_fixture = NULL; + } - bool ReportFixture(b2Fixture* fixture) - { - b2Body* body = fixture->GetBody(); - if (body->GetType() == b2_dynamicBody) - { - bool inside = fixture->TestPoint(m_point); - if (inside) - { - m_fixture = fixture; + bool ReportFixture(b2Fixture* fixture) + { + b2Body* body = fixture->GetBody(); + if (body->GetType() == b2_dynamicBody) + { + bool inside = fixture->TestPoint(m_point); + if (inside) + { + m_fixture = fixture; - // We are done, terminate the query. - return false; - } - } + // We are done, terminate the query. + return false; + } + } - // Continue the query. - return true; - } + // Continue the query. + return true; + } - b2Vec2 m_point; - b2Fixture* m_fixture; + b2Vec2 m_point; + b2Fixture* m_fixture; }; bool Test::MouseDown(const b2Vec2& p) { - m_mouseWorld = p; - - if (m_mouseJoint != NULL) - { - return false; - } + m_mouseWorld = p; + + if (m_mouseJoint != NULL) + { + return false; + } - // Make a small box. - b2AABB aabb; - b2Vec2 d; - d.Set(0.001f, 0.001f); - aabb.lowerBound = p - d; - aabb.upperBound = p + d; + // Make a small box. + b2AABB aabb; + b2Vec2 d; + d.Set(0.001f, 0.001f); + aabb.lowerBound = p - d; + aabb.upperBound = p + d; - // Query the world for overlapping shapes. - QueryCallback callback(p); - m_world->QueryAABB(&callback, aabb); + // Query the world for overlapping shapes. + QueryCallback callback(p); + m_world->QueryAABB(&callback, aabb); - if (callback.m_fixture) - { - b2Body* body = callback.m_fixture->GetBody(); - b2MouseJointDef md; - md.bodyA = m_groundBody; - md.bodyB = body; - md.target = p; - md.maxForce = 1000.0f * body->GetMass(); - m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md); - body->SetAwake(true); + if (callback.m_fixture) + { + b2Body* body = callback.m_fixture->GetBody(); + b2MouseJointDef md; + md.bodyA = m_groundBody; + md.bodyB = body; + md.target = p; + md.maxForce = 1000.0f * body->GetMass(); + m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md); + body->SetAwake(true); return true; - } + } + return false; } void Test::SpawnBomb(const b2Vec2& worldPt) { - m_bombSpawnPoint = worldPt; - m_bombSpawning = true; + m_bombSpawnPoint = worldPt; + m_bombSpawning = true; } void Test::CompleteBombSpawn(const b2Vec2& p) { - if (m_bombSpawning == false) - { - return; - } + if (m_bombSpawning == false) + { + return; + } - const float multiplier = 30.0f; - b2Vec2 vel = m_bombSpawnPoint - p; - vel *= multiplier; - LaunchBomb(m_bombSpawnPoint,vel); - m_bombSpawning = false; + const float multiplier = 30.0f; + b2Vec2 vel = m_bombSpawnPoint - p; + vel *= multiplier; + LaunchBomb(m_bombSpawnPoint,vel); + m_bombSpawning = false; } void Test::ShiftMouseDown(const b2Vec2& p) { - m_mouseWorld = p; - - if (m_mouseJoint != NULL) - { - return; - } + m_mouseWorld = p; + + if (m_mouseJoint != NULL) + { + return; + } - SpawnBomb(p); + SpawnBomb(p); } void Test::MouseUp(const b2Vec2& p) { - if (m_mouseJoint) - { - m_world->DestroyJoint(m_mouseJoint); - m_mouseJoint = NULL; - } - - if (m_bombSpawning) - { - CompleteBombSpawn(p); - } + if (m_mouseJoint) + { + m_world->DestroyJoint(m_mouseJoint); + m_mouseJoint = NULL; + } + + if (m_bombSpawning) + { + CompleteBombSpawn(p); + } } void Test::MouseMove(const b2Vec2& p) { - m_mouseWorld = p; - - if (m_mouseJoint) - { - m_mouseJoint->SetTarget(p); - } + m_mouseWorld = p; + + if (m_mouseJoint) + { + m_mouseJoint->SetTarget(p); + } } void Test::LaunchBomb() { - b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); - b2Vec2 v = -5.0f * p; - LaunchBomb(p, v); + b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); + b2Vec2 v = -5.0f * p; + LaunchBomb(p, v); } void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity) { - if (m_bomb) - { - m_world->DestroyBody(m_bomb); - m_bomb = NULL; - } + if (m_bomb) + { + m_world->DestroyBody(m_bomb); + m_bomb = NULL; + } - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = position; - bd.bullet = true; - m_bomb = m_world->CreateBody(&bd); - m_bomb->SetLinearVelocity(velocity); - - b2CircleShape circle; - circle.m_radius = 0.3f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = position; + bd.bullet = true; + m_bomb = m_world->CreateBody(&bd); + m_bomb->SetLinearVelocity(velocity); + + b2CircleShape circle; + circle.m_radius = 0.3f; - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 20.0f; - fd.restitution = 0.0f; - - b2Vec2 minV = position - b2Vec2(0.3f,0.3f); - b2Vec2 maxV = position + b2Vec2(0.3f,0.3f); - - b2AABB aabb; - aabb.lowerBound = minV; - aabb.upperBound = maxV; + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 20.0f; + fd.restitution = 0.0f; + + b2Vec2 minV = position - b2Vec2(0.3f,0.3f); + b2Vec2 maxV = position + b2Vec2(0.3f,0.3f); + + b2AABB aabb; + aabb.lowerBound = minV; + aabb.upperBound = maxV; - m_bomb->CreateFixture(&fd); + m_bomb->CreateFixture(&fd); } void Test::Step(Settings* settings) { - float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f); + float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f); - if (settings->pause) - { - if (settings->singleStep) - { - settings->singleStep = 0; - } - else - { - timeStep = 0.0f; - } + if (settings->pause) + { + if (settings->singleStep) + { + settings->singleStep = 0; + } + else + { + timeStep = 0.0f; + } - m_debugDraw.DrawString(5, m_textLine, "****PAUSED****"); - m_textLine += 15; - } + m_debugDraw.DrawString(5, m_textLine, "****PAUSED****"); + m_textLine += DRAW_STRING_NEW_LINE; + } - uint32 flags = 0; - flags += settings->drawShapes * b2Draw::e_shapeBit; - flags += settings->drawJoints * b2Draw::e_jointBit; - flags += settings->drawAABBs * b2Draw::e_aabbBit; - flags += settings->drawPairs * b2Draw::e_pairBit; - flags += settings->drawCOMs * b2Draw::e_centerOfMassBit; - m_debugDraw.SetFlags(flags); + uint32 flags = 0; + flags += settings->drawShapes * b2Draw::e_shapeBit; + flags += settings->drawJoints * b2Draw::e_jointBit; + flags += settings->drawAABBs * b2Draw::e_aabbBit; + flags += settings->drawCOMs * b2Draw::e_centerOfMassBit; + m_debugDraw.SetFlags(flags); - m_world->SetWarmStarting(settings->enableWarmStarting > 0); - m_world->SetContinuousPhysics(settings->enableContinuous > 0); - m_world->SetSubStepping(settings->enableSubStepping > 0); + m_world->SetAllowSleeping(settings->enableSleep > 0); + m_world->SetWarmStarting(settings->enableWarmStarting > 0); + m_world->SetContinuousPhysics(settings->enableContinuous > 0); + m_world->SetSubStepping(settings->enableSubStepping > 0); - m_pointCount = 0; + m_pointCount = 0; - m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations); + m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations); - m_world->DrawDebugData(); + m_world->DrawDebugData(); - if (timeStep > 0.0f) - { - ++m_stepCount; - } + if (timeStep > 0.0f) + { + ++m_stepCount; + } - if (settings->drawStats) - { - int32 bodyCount = m_world->GetBodyCount(); - int32 contactCount = m_world->GetContactCount(); - int32 jointCount = m_world->GetJointCount(); - m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); - m_textLine += 15; + if (settings->drawStats) + { + int32 bodyCount = m_world->GetBodyCount(); + int32 contactCount = m_world->GetContactCount(); + int32 jointCount = m_world->GetJointCount(); + m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); + m_textLine += DRAW_STRING_NEW_LINE; - int32 proxyCount = m_world->GetProxyCount(); - int32 height = m_world->GetTreeHeight(); - int32 balance = m_world->GetTreeBalance(); - float32 quality = m_world->GetTreeQuality(); - m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); - m_textLine += 15; - } + int32 proxyCount = m_world->GetProxyCount(); + int32 height = m_world->GetTreeHeight(); + int32 balance = m_world->GetTreeBalance(); + float32 quality = m_world->GetTreeQuality(); + m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); + m_textLine += DRAW_STRING_NEW_LINE; + } - // Track maximum profile times - { - const b2Profile& p = m_world->GetProfile(); - m_maxProfile.step = b2Max(m_maxProfile.step, p.step); - m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); - m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); - m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); - m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); - m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); - m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); - m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); + // Track maximum profile times + { + const b2Profile& p = m_world->GetProfile(); + m_maxProfile.step = b2Max(m_maxProfile.step, p.step); + m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); + m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); + m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); + m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); + m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); + m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); + m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); - m_totalProfile.step += p.step; - m_totalProfile.collide += p.collide; - m_totalProfile.solve += p.solve; - m_totalProfile.solveInit += p.solveInit; - m_totalProfile.solveVelocity += p.solveVelocity; - m_totalProfile.solvePosition += p.solvePosition; - m_totalProfile.solveTOI += p.solveTOI; - m_totalProfile.broadphase += p.broadphase; - } + m_totalProfile.step += p.step; + m_totalProfile.collide += p.collide; + m_totalProfile.solve += p.solve; + m_totalProfile.solveInit += p.solveInit; + m_totalProfile.solveVelocity += p.solveVelocity; + m_totalProfile.solvePosition += p.solvePosition; + m_totalProfile.solveTOI += p.solveTOI; + m_totalProfile.broadphase += p.broadphase; + } - if (settings->drawProfile) - { - const b2Profile& p = m_world->GetProfile(); + if (settings->drawProfile) + { + const b2Profile& p = m_world->GetProfile(); - b2Profile aveProfile; - memset(&aveProfile, 0, sizeof(b2Profile)); - if (m_stepCount > 0) - { - float32 scale = 1.0f / m_stepCount; - aveProfile.step = scale * m_totalProfile.step; - aveProfile.collide = scale * m_totalProfile.collide; - aveProfile.solve = scale * m_totalProfile.solve; - aveProfile.solveInit = scale * m_totalProfile.solveInit; - aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; - aveProfile.solvePosition = scale * m_totalProfile.solvePosition; - aveProfile.solveTOI = scale * m_totalProfile.solveTOI; - aveProfile.broadphase = scale * m_totalProfile.broadphase; - } + b2Profile aveProfile; + memset(&aveProfile, 0, sizeof(b2Profile)); + if (m_stepCount > 0) + { + float32 scale = 1.0f / m_stepCount; + aveProfile.step = scale * m_totalProfile.step; + aveProfile.collide = scale * m_totalProfile.collide; + aveProfile.solve = scale * m_totalProfile.solve; + aveProfile.solveInit = scale * m_totalProfile.solveInit; + aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; + aveProfile.solvePosition = scale * m_totalProfile.solvePosition; + aveProfile.solveTOI = scale * m_totalProfile.solveTOI; + aveProfile.broadphase = scale * m_totalProfile.broadphase; + } - m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); - m_textLine += 15; - } + m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); + m_textLine += DRAW_STRING_NEW_LINE; + } - if (m_mouseJoint) - { - b2Vec2 p1 = m_mouseJoint->GetAnchorB(); - b2Vec2 p2 = m_mouseJoint->GetTarget(); + if (m_mouseJoint) + { + b2Vec2 p1 = m_mouseJoint->GetAnchorB(); + b2Vec2 p2 = m_mouseJoint->GetTarget(); - b2Color c; - c.Set(0.0f, 1.0f, 0.0f); - m_debugDraw.DrawPoint(p1, 4.0f, c); - m_debugDraw.DrawPoint(p2, 4.0f, c); + b2Color c; + c.Set(0.0f, 1.0f, 0.0f); + m_debugDraw.DrawPoint(p1, 4.0f, c); + m_debugDraw.DrawPoint(p2, 4.0f, c); - c.Set(0.8f, 0.8f, 0.8f); - m_debugDraw.DrawSegment(p1, p2, c); - } - - if (m_bombSpawning) - { - b2Color c; - c.Set(0.0f, 0.0f, 1.0f); - m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); + c.Set(0.8f, 0.8f, 0.8f); + m_debugDraw.DrawSegment(p1, p2, c); + } + + if (m_bombSpawning) + { + b2Color c; + c.Set(0.0f, 0.0f, 1.0f); + m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); - c.Set(0.8f, 0.8f, 0.8f); - m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); - } + c.Set(0.8f, 0.8f, 0.8f); + m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); + } - if (settings->drawContactPoints) - { - //const float32 k_impulseScale = 0.1f; - const float32 k_axisScale = 0.3f; + if (settings->drawContactPoints) + { + const float32 k_impulseScale = 0.1f; + const float32 k_axisScale = 0.3f; - for (int32 i = 0; i < m_pointCount; ++i) - { - auto point = m_points + i; + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; - if (point->state == b2_addState) - { - // Add - m_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); - } - else if (point->state == b2_persistState) - { - // Persist - m_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); - } + if (point->state == b2_addState) + { + // Add + m_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); + } + else if (point->state == b2_persistState) + { + // Persist + m_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); + } - if (settings->drawContactNormals == 1) - { - b2Vec2 p1 = point->position; - b2Vec2 p2 = p1 + k_axisScale * point->normal; - m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); - } - else if (settings->drawContactForces == 1) - { - //b2Vec2 p1 = point->position; - //b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal; - //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } + if (settings->drawContactNormals == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_axisScale * point->normal; + m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); + } + else if (settings->drawContactImpulse == 1) + { + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; + m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } - if (settings->drawFrictionForces == 1) - { - //b2Vec2 tangent = b2Cross(point->normal, 1.0f); - //b2Vec2 p1 = point->position; - //b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent; - //DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); - } - } - } + if (settings->drawFrictionImpulse == 1) + { + b2Vec2 tangent = b2Cross(point->normal, 1.0f); + b2Vec2 p1 = point->position; + b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; + m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); + } + } + } +} + +void Test::ShiftOrigin(const b2Vec2& newOrigin) +{ + m_world->ShiftOrigin(newOrigin); } diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h index a2dc2b9243..7ec5b1c9f5 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h @@ -29,78 +29,80 @@ struct Settings; typedef Test* TestCreateFcn(); -#define RAND_LIMIT 32767 +#define RAND_LIMIT 32767 +#define DRAW_STRING_NEW_LINE 25 /// Random number in range [-1,1] inline float32 RandomFloat() { - float32 r = (float32)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = 2.0f * r - 1.0f; - return r; + float32 r = (float32)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = 2.0f * r - 1.0f; + return r; } /// Random floating point number in range [lo, hi] inline float32 RandomFloat(float32 lo, float32 hi) { - float32 r = (float32)(std::rand() & (RAND_LIMIT)); - r /= RAND_LIMIT; - r = (hi - lo) * r + lo; - return r; + float32 r = (float32)(std::rand() & (RAND_LIMIT)); + r /= RAND_LIMIT; + r = (hi - lo) * r + lo; + return r; } /// Test settings. Some can be controlled in the GUI. struct Settings { - Settings() : - viewCenter(0.0f, 20.0f), - hz(60.0f), - velocityIterations(8), - positionIterations(3), - drawShapes(1), - drawJoints(1), - drawAABBs(0), - drawPairs(0), - drawContactPoints(0), - drawContactNormals(0), - drawContactForces(0), - drawFrictionForces(0), - drawCOMs(0), - drawStats(0), - drawProfile(0), - enableWarmStarting(1), - enableContinuous(1), - enableSubStepping(0), - pause(0), - singleStep(0) - {} + Settings() + { + viewCenter.Set(0.0f, 20.0f); + hz = 60.0f; + velocityIterations = 8; + positionIterations = 3; + drawShapes = 1; + drawJoints = 1; + drawAABBs = 0; + drawContactPoints = 0; + drawContactNormals = 0; + drawContactImpulse = 0; + drawFrictionImpulse = 0; + drawCOMs = 0; + drawStats = 0; + drawProfile = 0; + enableWarmStarting = 1; + enableContinuous = 1; + enableSubStepping = 0; + enableSleep = 1; + pause = 0; + singleStep = 0; + } - b2Vec2 viewCenter; - float32 hz; - int32 velocityIterations; - int32 positionIterations; - int32 drawShapes; - int32 drawJoints; - int32 drawAABBs; - int32 drawPairs; - int32 drawContactPoints; - int32 drawContactNormals; - int32 drawContactForces; - int32 drawFrictionForces; - int32 drawCOMs; - int32 drawStats; - int32 drawProfile; - int32 enableWarmStarting; - int32 enableContinuous; - int32 enableSubStepping; - int32 pause; - int32 singleStep; + b2Vec2 viewCenter; + float32 hz; + int32 velocityIterations; + int32 positionIterations; + int32 drawShapes; + int32 drawJoints; + int32 drawAABBs; + int32 drawContactPoints; + int32 drawContactNormals; + int32 drawContactImpulse; + int32 drawFrictionImpulse; + int32 drawCOMs; + int32 drawStats; + int32 drawProfile; + int32 enableWarmStarting; + int32 enableContinuous; + int32 enableSubStepping; + int32 enableSleep; + int32 pause; + int32 singleStep; }; struct TestEntry { - const char *name; - TestCreateFcn *createFcn; + const char *name; + TestCreateFcn *createFcn; }; extern TestEntry g_testEntries[]; @@ -110,80 +112,85 @@ extern TestEntry g_testEntries[]; class DestructionListener : public b2DestructionListener { public: - void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } - void SayGoodbye(b2Joint* joint); + void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } + void SayGoodbye(b2Joint* joint); - Test* test; + Test* test; }; const int32 k_maxContactPoints = 2048; struct ContactPoint { - b2Fixture* fixtureA; - b2Fixture* fixtureB; - b2Vec2 normal; - b2Vec2 position; - b2PointState state; + b2Fixture* fixtureA; + b2Fixture* fixtureB; + b2Vec2 normal; + b2Vec2 position; + b2PointState state; + float32 normalImpulse; + float32 tangentImpulse; + float32 separation; }; class Test : public b2ContactListener { public: - Test(); - virtual ~Test(); + Test(); + virtual ~Test(); - void SetTextLine(int32 line) { m_textLine = line; } - void DrawTitle(int x, int y, const char *string); - virtual void Step(Settings* settings); - virtual void Keyboard(unsigned char key) { B2_NOT_USED(key); } - virtual void KeyboardUp(unsigned char key) { B2_NOT_USED(key); } - void ShiftMouseDown(const b2Vec2& p); - virtual bool MouseDown(const b2Vec2& p); - virtual void MouseUp(const b2Vec2& p); - void MouseMove(const b2Vec2& p); - void LaunchBomb(); - void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); - - void SpawnBomb(const b2Vec2& worldPt); - void CompleteBombSpawn(const b2Vec2& p); + void DrawTitle(const char *string); + virtual void Step(Settings* settings); + virtual void Keyboard(unsigned char key) { B2_NOT_USED(key); } + virtual void KeyboardUp(unsigned char key) { B2_NOT_USED(key); } + void ShiftMouseDown(const b2Vec2& p); + virtual bool MouseDown(const b2Vec2& p); + virtual void MouseUp(const b2Vec2& p); + void MouseMove(const b2Vec2& p); + void LaunchBomb(); + void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); + + void SpawnBomb(const b2Vec2& worldPt); + void CompleteBombSpawn(const b2Vec2& p); - // Let derived tests know that a joint was destroyed. - virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } + // Let derived tests know that a joint was destroyed. + virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } - // Callbacks for derived classes. - virtual void BeginContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void EndContact(b2Contact* contact) override { B2_NOT_USED(contact); } - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } + // Callbacks for derived classes. + virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } + virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } + virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); + virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + B2_NOT_USED(contact); + B2_NOT_USED(impulse); + } -public: - friend class DestructionListener; - friend class BoundaryListener; - friend class ContactListener; + void ShiftOrigin(const b2Vec2& newOrigin); - b2Body* m_groundBody; - b2AABB m_worldAABB; - ContactPoint m_points[k_maxContactPoints]; - int32 m_pointCount; - DestructionListener m_destructionListener; - GLESDebugDraw m_debugDraw; - int32 m_textLine; - b2World* m_world; - b2Body* m_bomb; - b2MouseJoint* m_mouseJoint; - b2Vec2 m_bombSpawnPoint; - bool m_bombSpawning; - b2Vec2 m_mouseWorld; - int32 m_stepCount; +protected: + friend class DestructionListener; + friend class BoundaryListener; + friend class ContactListener; + friend class Box2DView; - b2Profile m_maxProfile; - b2Profile m_totalProfile; + b2Body* m_groundBody; + b2AABB m_worldAABB; + ContactPoint m_points[k_maxContactPoints]; + int32 m_pointCount; + DestructionListener m_destructionListener; + GLESDebugDraw m_debugDraw; + int32 m_textLine; + b2World* m_world; + b2Body* m_bomb; + b2MouseJoint* m_mouseJoint; + b2Vec2 m_bombSpawnPoint; + bool m_bombSpawning; + b2Vec2 m_mouseWorld; + int32 m_stepCount; + + b2Profile m_maxProfile; + b2Profile m_totalProfile; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp index 29428ad219..5fb831212a 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp @@ -15,12 +15,10 @@ * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ - -#include "Test.h" - #include using namespace std; +#include "Test.h" #include "Tests/AddPair.h" #include "Tests/ApplyForce.h" #include "Tests/BodyTypes.h" @@ -36,6 +34,8 @@ using namespace std; #include "Tests/CollisionProcessing.h" #include "Tests/CompoundShapes.h" #include "Tests/Confined.h" +#include "Tests/ConvexHull.h" +#include "Tests/ConveyorBelt.h" #include "Tests/DistanceTest.h" #include "Tests/Dominos.h" #include "Tests/DumpShell.h" @@ -43,6 +43,9 @@ using namespace std; #include "Tests/EdgeShapes.h" #include "Tests/EdgeTest.h" #include "Tests/Gears.h" +#include "Tests/Mobile.h" +#include "Tests/MobileBalanced.h" +#include "Tests/MotorJoint.h" #include "Tests/OneSidedPlatform.h" #include "Tests/Pinball.h" #include "Tests/PolyCollision.h" @@ -52,7 +55,6 @@ using namespace std; #include "Tests/Pyramid.h" #include "Tests/RayCast.h" #include "Tests/Revolute.h" -//#include "Tests/Rope.h" #include "Tests/RopeJoint.h" #include "Tests/SensorTest.h" #include "Tests/ShapeEditing.h" @@ -69,52 +71,56 @@ using namespace std; TestEntry g_testEntries[] = { - {"Tumbler", Tumbler::Create}, - {"Tiles", Tiles::Create}, - {"Dump Shell", DumpShell::Create}, - {"Gears", Gears::Create}, - {"Cantilever", Cantilever::Create}, - {"Varying Restitution", VaryingRestitution::Create}, - {"Character Collision", CharacterCollision::Create}, - {"Edge Test", EdgeTest::Create}, - {"Body Types", BodyTypes::Create}, - {"Shape Editing", ShapeEditing::Create}, - {"Car", Car::Create}, - {"Apply Force", ApplyForce::Create}, - {"Prismatic", Prismatic::Create}, - {"Vertical Stack", VerticalStack::Create}, - {"SphereStack", SphereStack::Create}, - {"Revolute", Revolute::Create}, - {"Pulleys", Pulleys::Create}, - {"Polygon Shapes", PolyShapes::Create}, - //{"Rope", Rope::Create}, - {"Web", Web::Create}, - {"RopeJoint", RopeJoint::Create}, - {"One-Sided Platform", OneSidedPlatform::Create}, - {"Pinball", Pinball::Create}, - {"Bullet Test", BulletTest::Create}, - {"Continuous Test", ContinuousTest::Create}, - {"Time of Impact", TimeOfImpact::Create}, - {"Ray-Cast", RayCast::Create}, - {"Confined", Confined::Create}, - {"Pyramid", Pyramid::Create}, - {"Theo Jansen's Walker", TheoJansen::Create}, - {"Edge Shapes", EdgeShapes::Create}, - {"PolyCollision", PolyCollision::Create}, - {"Bridge", Bridge::Create}, - {"Breakable", Breakable::Create}, - {"Chain", Chain::Create}, - {"Collision Filtering", CollisionFiltering::Create}, - {"Collision Processing", CollisionProcessing::Create}, - {"Compound Shapes", CompoundShapes::Create}, - {"Distance Test", DistanceTest::Create}, - {"Dominos", Dominos::Create}, - {"Dynamic Tree", DynamicTreeTest::Create}, - {"Sensor Test", SensorTest::Create}, - {"Slider Crank", SliderCrank::Create}, - {"Varying Friction", VaryingFriction::Create}, - {"Add Pair Stress Test", AddPair::Create}, -// {NULL, NULL} + {"Ray-Cast", RayCast::Create}, + {"Dump Shell", DumpShell::Create}, + {"Convex Hull", ConvexHull::Create}, + {"Apply Force", ApplyForce::Create}, + {"Continuous Test", ContinuousTest::Create}, + {"Time of Impact", TimeOfImpact::Create}, + {"Motor Joint", MotorJoint::Create}, + {"One-Sided Platform", OneSidedPlatform::Create}, + {"Mobile", Mobile::Create}, + {"MobileBalanced", MobileBalanced::Create}, + {"Conveyor Belt", ConveyorBelt::Create}, + {"Gears", Gears::Create}, + {"Varying Restitution", VaryingRestitution::Create}, + {"Tumbler", Tumbler::Create}, + {"Tiles", Tiles::Create}, + {"Cantilever", Cantilever::Create}, + {"Character Collision", CharacterCollision::Create}, + {"Edge Test", EdgeTest::Create}, + {"Body Types", BodyTypes::Create}, + {"Shape Editing", ShapeEditing::Create}, + {"Car", Car::Create}, + {"Prismatic", Prismatic::Create}, + {"Vertical Stack", VerticalStack::Create}, + {"SphereStack", SphereStack::Create}, + {"Revolute", Revolute::Create}, + {"Pulleys", Pulleys::Create}, + {"Polygon Shapes", PolyShapes::Create}, + {"Web", Web::Create}, + {"RopeJoint", RopeJoint::Create}, + {"Pinball", Pinball::Create}, + {"Bullet Test", BulletTest::Create}, + {"Confined", Confined::Create}, + {"Pyramid", Pyramid::Create}, + {"Theo Jansen's Walker", TheoJansen::Create}, + {"Edge Shapes", EdgeShapes::Create}, + {"PolyCollision", PolyCollision::Create}, + {"Bridge", Bridge::Create}, + {"Breakable", Breakable::Create}, + {"Chain", Chain::Create}, + {"Collision Filtering", CollisionFiltering::Create}, + {"Collision Processing", CollisionProcessing::Create}, + {"Compound Shapes", CompoundShapes::Create}, + {"Distance Test", DistanceTest::Create}, + {"Dominos", Dominos::Create}, + {"Dynamic Tree", DynamicTreeTest::Create}, + {"Sensor Test", SensorTest::Create}, + {"Slider Crank", SliderCrank::Create}, + {"Varying Friction", VaryingFriction::Create}, + {"Add Pair Stress Test", AddPair::Create}, + {NULL, NULL} }; -int g_totalEntries = sizeof(g_testEntries) / sizeof(g_testEntries[0]); \ No newline at end of file +int g_totalEntries = sizeof(g_testEntries) / sizeof(g_testEntries[0]); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h index 54d6e24814..6f995e0ce8 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h @@ -1,3 +1,20 @@ +/* +* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ #ifndef AddPair_H #define AddPair_H @@ -6,46 +23,46 @@ class AddPair : public Test { public: - AddPair() - { - m_world->SetGravity(b2Vec2(0.0f,0.0f)); - { - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.1f; + AddPair() + { + m_world->SetGravity(b2Vec2(0.0f,0.0f)); + { + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.1f; - float minX = -6.0f; - float maxX = 0.0f; - float minY = 4.0f; - float maxY = 6.0f; - - for (int32 i = 0; i < 400; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = b2Vec2(RandomFloat(minX,maxX),RandomFloat(minY,maxY)); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 0.01f); - } - } - - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f,5.0f); - bd.bullet = true; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(150.0f, 0.0f)); - } - } + float minX = -6.0f; + float maxX = 0.0f; + float minY = 4.0f; + float maxY = 6.0f; + + for (int32 i = 0; i < 400; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = b2Vec2(RandomFloat(minX,maxX),RandomFloat(minY,maxY)); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 0.01f); + } + } + + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f,5.0f); + bd.bullet = true; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(150.0f, 0.0f)); + } + } - static Test* Create() - { - return new AddPair; - } + static Test* Create() + { + return new AddPair; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h index a98d314af8..b4bd10f425 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h @@ -22,159 +22,159 @@ class ApplyForce : public Test { public: - ApplyForce() - { - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + ApplyForce() + { + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - const float32 k_restitution = 0.4f; + const float32 k_restitution = 0.4f; - b2Body* ground; - { - b2BodyDef bd; - bd.position.Set(0.0f, 20.0f); - ground = m_world->CreateBody(&bd); + b2Body* ground; + { + b2BodyDef bd; + bd.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; + b2EdgeShape shape; - b2FixtureDef sd; - sd.shape = &shape; - sd.density = 0.0f; - sd.restitution = k_restitution; + b2FixtureDef sd; + sd.shape = &shape; + sd.density = 0.0f; + sd.restitution = k_restitution; - // Left vertical - shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Left vertical + shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Right vertical - shape.Set(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Right vertical + shape.Set(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Top horizontal - shape.Set(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&sd); + // Top horizontal + shape.Set(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&sd); - // Bottom horizontal - shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); - ground->CreateFixture(&sd); - } + // Bottom horizontal + shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f)); + ground->CreateFixture(&sd); + } - { - b2Transform xf1; - xf1.q.Set(0.3524f * b2_pi); - xf1.p = xf1.q.GetXAxis(); + { + b2Transform xf1; + xf1.q.Set(0.3524f * b2_pi); + xf1.p = xf1.q.GetXAxis(); - b2Vec2 vertices[3]; - vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); - - b2PolygonShape poly1; - poly1.Set(vertices, 3); + b2Vec2 vertices[3]; + vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly1; + poly1.Set(vertices, 3); - b2FixtureDef sd1; - sd1.shape = &poly1; - sd1.density = 4.0f; + b2FixtureDef sd1; + sd1.shape = &poly1; + sd1.density = 4.0f; - b2Transform xf2; - xf2.q.Set(-0.3524f * b2_pi); - xf2.p = -xf2.q.GetXAxis(); + b2Transform xf2; + xf2.q.Set(-0.3524f * b2_pi); + xf2.p = -xf2.q.GetXAxis(); - vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); - - b2PolygonShape poly2; - poly2.Set(vertices, 3); + vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); + + b2PolygonShape poly2; + poly2.Set(vertices, 3); - b2FixtureDef sd2; - sd2.shape = &poly2; - sd2.density = 2.0f; + b2FixtureDef sd2; + sd2.shape = &poly2; + sd2.density = 2.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.angularDamping = 5.0f; - bd.linearDamping = 0.1f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.angularDamping = 2.0f; + bd.linearDamping = 0.5f; - bd.position.Set(0.0f, 2.0); - bd.angle = b2_pi; - bd.allowSleep = false; - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&sd1); - m_body->CreateFixture(&sd2); - } + bd.position.Set(0.0f, 2.0); + bd.angle = b2_pi; + bd.allowSleep = false; + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&sd1); + m_body->CreateFixture(&sd2); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 5.0f + 1.54f * i); - b2Body* body = m_world->CreateBody(&bd); + bd.position.Set(0.0f, 5.0f + 1.54f * i); + b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + body->CreateFixture(&fd); - float32 gravity = 10.0f; - float32 I = body->GetInertia(); - float32 mass = body->GetMass(); + float32 gravity = 10.0f; + float32 I = body->GetInertia(); + float32 mass = body->GetMass(); - // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) - float32 radius = b2Sqrt(2.0f * I / mass); + // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) + float32 radius = b2Sqrt(2.0f * I / mass); - b2FrictionJointDef jd; - jd.localAnchorA.SetZero(); - jd.localAnchorB.SetZero(); - jd.bodyA = ground; - jd.bodyB = body; - jd.collideConnected = true; - jd.maxForce = mass * gravity; - jd.maxTorque = mass * radius * gravity; + b2FrictionJointDef jd; + jd.localAnchorA.SetZero(); + jd.localAnchorB.SetZero(); + jd.bodyA = ground; + jd.bodyB = body; + jd.collideConnected = true; + jd.maxForce = mass * gravity; + jd.maxTorque = mass * radius * gravity; - m_world->CreateJoint(&jd); - } - } - } + m_world->CreateJoint(&jd); + } + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'w': - { - b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -200.0f)); - b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 2.0f)); - m_body->ApplyForce(f, p); - } - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'w': + { + b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -200.0f)); + b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 2.0f)); + m_body->ApplyForce(f, p, true); + } + break; - case 'a': - { - m_body->ApplyTorque(50.0f); - } - break; + case 'a': + { + m_body->ApplyTorque(50.0f, true); + } + break; - case 'd': - { - m_body->ApplyTorque(-50.0f); - } - break; - } - } + case 'd': + { + m_body->ApplyTorque(-50.0f, true); + } + break; + } + } - static Test* Create() - { - return new ApplyForce; - } + static Test* Create() + { + return new ApplyForce; + } - b2Body* m_body; + b2Body* m_body; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h index c3710f84ee..050b611aca 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h @@ -22,138 +22,138 @@ class BodyTypes : public Test { public: - BodyTypes() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + BodyTypes() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + b2EdgeShape shape; + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - b2FixtureDef fd; - fd.shape = &shape; + b2FixtureDef fd; + fd.shape = &shape; - ground->CreateFixture(&fd); - } + ground->CreateFixture(&fd); + } - // Define attachment - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 3.0f); - m_attachment = m_world->CreateBody(&bd); + // Define attachment + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 3.0f); + m_attachment = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); - m_attachment->CreateFixture(&shape, 2.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); + m_attachment->CreateFixture(&shape, 2.0f); + } - // Define platform - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.0f, 5.0f); - m_platform = m_world->CreateBody(&bd); + // Define platform + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.0f, 5.0f); + m_platform = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; - m_platform->CreateFixture(&fd); + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + m_platform->CreateFixture(&fd); - b2RevoluteJointDef rjd; - rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); - rjd.maxMotorTorque = 50.0f; - rjd.enableMotor = true; - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); + rjd.maxMotorTorque = 50.0f; + rjd.enableMotor = true; + m_world->CreateJoint(&rjd); - b2PrismaticJointDef pjd; - pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); + b2PrismaticJointDef pjd; + pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; - pjd.lowerTranslation = -10.0f; - pjd.upperTranslation = 10.0f; - pjd.enableLimit = true; + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; + pjd.lowerTranslation = -10.0f; + pjd.upperTranslation = 10.0f; + pjd.enableLimit = true; - m_world->CreateJoint(&pjd); + m_world->CreateJoint(&pjd); - m_speed = 3.0f; - } + m_speed = 3.0f; + } - // Create a payload - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 8.0f); - b2Body* body = m_world->CreateBody(&bd); + // Create a payload + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.75f, 0.75f); + b2PolygonShape shape; + shape.SetAsBox(0.75f, 0.75f); - b2FixtureDef fd; - fd.shape = &shape; - fd.friction = 0.6f; - fd.density = 2.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; - body->CreateFixture(&fd); - } - } + body->CreateFixture(&fd); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'd': - m_platform->SetType(b2_dynamicBody); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'd': + m_platform->SetType(b2_dynamicBody); + break; - case 's': - m_platform->SetType(b2_staticBody); - break; + case 's': + m_platform->SetType(b2_staticBody); + break; - case 'k': - m_platform->SetType(b2_kinematicBody); - m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); - m_platform->SetAngularVelocity(0.0f); - break; - } - } + case 'k': + m_platform->SetType(b2_kinematicBody); + m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); + m_platform->SetAngularVelocity(0.0f); + break; + } + } - void Step(Settings* settings) - { - // Drive the kinematic body. - if (m_platform->GetType() == b2_kinematicBody) - { - b2Vec2 p = m_platform->GetTransform().p; - b2Vec2 v = m_platform->GetLinearVelocity(); + void Step(Settings* settings) + { + // Drive the kinematic body. + if (m_platform->GetType() == b2_kinematicBody) + { + b2Vec2 p = m_platform->GetTransform().p; + b2Vec2 v = m_platform->GetLinearVelocity(); - if ((p.x < -10.0f && v.x < 0.0f) || - (p.x > 10.0f && v.x > 0.0f)) - { - v.x = -v.x; - m_platform->SetLinearVelocity(v); - } - } + if ((p.x < -10.0f && v.x < 0.0f) || + (p.x > 10.0f && v.x > 0.0f)) + { + v.x = -v.x; + m_platform->SetLinearVelocity(v); + } + } - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); - m_textLine += 15; - } + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new BodyTypes; - } + static Test* Create() + { + return new BodyTypes; + } - b2Body* m_attachment; - b2Body* m_platform; - float32 m_speed; + b2Body* m_attachment; + b2Body* m_platform; + float32 m_speed; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h index b8c71de8d0..521ae7a090 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h @@ -24,132 +24,132 @@ class Breakable : public Test { public: - enum - { - e_count = 7 - }; + enum + { + e_count = 7 + }; - Breakable() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + Breakable() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Breakable dynamic body - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 40.0f); - bd.angle = 0.25f * b2_pi; - m_body1 = m_world->CreateBody(&bd); + // Breakable dynamic body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 40.0f); + bd.angle = 0.25f * b2_pi; + m_body1 = m_world->CreateBody(&bd); - m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); - m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); + m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); + m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); - m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); - m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); - } + m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); + m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); + } - m_break = false; - m_broke = false; - } + m_break = false; + m_broke = false; + } - void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) - { - if (m_broke) - { - // The body already broke. - return; - } + void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + if (m_broke) + { + // The body already broke. + return; + } - // Should the body break? - int32 count = contact->GetManifold()->pointCount; + // Should the body break? + int32 count = contact->GetManifold()->pointCount; - float32 maxImpulse = 0.0f; - for (int32 i = 0; i < count; ++i) - { - maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); - } + float32 maxImpulse = 0.0f; + for (int32 i = 0; i < count; ++i) + { + maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); + } - if (maxImpulse > 40.0f) - { - // Flag the body for breaking. - m_break = true; - } - } + if (maxImpulse > 40.0f) + { + // Flag the body for breaking. + m_break = true; + } + } - void Break() - { - // Create two bodies from one. - b2Body* body1 = m_piece1->GetBody(); - b2Vec2 center = body1->GetWorldCenter(); + void Break() + { + // Create two bodies from one. + b2Body* body1 = m_piece1->GetBody(); + b2Vec2 center = body1->GetWorldCenter(); - body1->DestroyFixture(m_piece2); - m_piece2 = NULL; + body1->DestroyFixture(m_piece2); + m_piece2 = NULL; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = body1->GetPosition(); - bd.angle = body1->GetAngle(); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = body1->GetPosition(); + bd.angle = body1->GetAngle(); - b2Body* body2 = m_world->CreateBody(&bd); - m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); + b2Body* body2 = m_world->CreateBody(&bd); + m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); - // Compute consistent velocities for new bodies based on - // cached velocity. - b2Vec2 center1 = body1->GetWorldCenter(); - b2Vec2 center2 = body2->GetWorldCenter(); - - b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); - b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); + // Compute consistent velocities for new bodies based on + // cached velocity. + b2Vec2 center1 = body1->GetWorldCenter(); + b2Vec2 center2 = body2->GetWorldCenter(); + + b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); + b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); - body1->SetAngularVelocity(m_angularVelocity); - body1->SetLinearVelocity(velocity1); + body1->SetAngularVelocity(m_angularVelocity); + body1->SetLinearVelocity(velocity1); - body2->SetAngularVelocity(m_angularVelocity); - body2->SetLinearVelocity(velocity2); - } + body2->SetAngularVelocity(m_angularVelocity); + body2->SetLinearVelocity(velocity2); + } - void Step(Settings* settings) - { - if (m_break) - { - Break(); - m_broke = true; - m_break = false; - } + void Step(Settings* settings) + { + if (m_break) + { + Break(); + m_broke = true; + m_break = false; + } - // Cache velocities to improve movement on breakage. - if (m_broke == false) - { - m_velocity = m_body1->GetLinearVelocity(); - m_angularVelocity = m_body1->GetAngularVelocity(); - } + // Cache velocities to improve movement on breakage. + if (m_broke == false) + { + m_velocity = m_body1->GetLinearVelocity(); + m_angularVelocity = m_body1->GetAngularVelocity(); + } - Test::Step(settings); - } + Test::Step(settings); + } - static Test* Create() - { - return new Breakable; - } + static Test* Create() + { + return new Breakable; + } - b2Body* m_body1; - b2Vec2 m_velocity; - float32 m_angularVelocity; - b2PolygonShape m_shape1; - b2PolygonShape m_shape2; - b2Fixture* m_piece1; - b2Fixture* m_piece2; + b2Body* m_body1; + b2Vec2 m_velocity; + float32 m_angularVelocity; + b2PolygonShape m_shape1; + b2PolygonShape m_shape2; + b2Fixture* m_piece1; + b2Fixture* m_piece2; - bool m_broke; - bool m_break; + bool m_broke; + bool m_break; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h index b9816bdd0b..25492ce4cb 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h @@ -23,103 +23,103 @@ class Bridge : public Test { public: - enum - { - e_count = 30 - }; + enum + { + e_count = 30 + }; - Bridge() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Bridge() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; - b2RevoluteJointDef jd; + b2RevoluteJointDef jd; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - if (i == (e_count >> 1)) - { - m_middle = body; - } - prevBody = body; - } + if (i == (e_count >> 1)) + { + m_middle = body; + } + prevBody = body; + } - b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } + b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); - b2PolygonShape shape; - shape.Set(vertices, 3); + b2PolygonShape shape; + shape.Set(vertices, 3); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } - for (int32 i = 0; i < 3; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; + for (int32 i = 0; i < 3; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - static Test* Create() - { - return new Bridge; - } + static Test* Create() + { + return new Bridge; + } - b2Body* m_middle; + b2Body* m_middle; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h index 1c9a7832d0..6f246090c8 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h @@ -23,114 +23,114 @@ class BulletTest : public Test { public: - BulletTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); + BulletTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape edge; + b2EdgeShape edge; - edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); + edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 4.0f); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 4.0f); - b2PolygonShape box; - box.SetAsBox(2.0f, 0.1f); + b2PolygonShape box; + box.SetAsBox(2.0f, 0.1f); - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&box, 1.0f); + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&box, 1.0f); - box.SetAsBox(0.25f, 0.25f); + box.SetAsBox(0.25f, 0.25f); - //m_x = RandomFloat(-1.0f, 1.0f); - m_x = 0.20352793f; - bd.position.Set(m_x, 10.0f); - bd.bullet = true; + //m_x = RandomFloat(-1.0f, 1.0f); + m_x = 0.20352793f; + bd.position.Set(m_x, 10.0f); + bd.bullet = true; - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&box, 100.0f); + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&box, 100.0f); - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } - void Launch() - { - m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); - m_body->SetLinearVelocity(b2Vec2_zero); - m_body->SetAngularVelocity(0.0f); + void Launch() + { + m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); + m_body->SetLinearVelocity(b2Vec2_zero); + m_body->SetAngularVelocity(0.0f); - m_x = RandomFloat(-1.0f, 1.0f); - m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); - m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - m_bullet->SetAngularVelocity(0.0f); + m_x = RandomFloat(-1.0f, 1.0f); + m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); + m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + m_bullet->SetAngularVelocity(0.0f); - extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; - extern int32 b2_toiRootIters, b2_toiMaxRootIters; + extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; + extern int32 b2_toiRootIters, b2_toiMaxRootIters; - b2_gjkCalls = 0; - b2_gjkIters = 0; - b2_gjkMaxIters = 0; + b2_gjkCalls = 0; + b2_gjkIters = 0; + b2_gjkMaxIters = 0; - b2_toiCalls = 0; - b2_toiIters = 0; - b2_toiMaxIters = 0; - b2_toiRootIters = 0; - b2_toiMaxRootIters = 0; - } + b2_toiCalls = 0; + b2_toiIters = 0; + b2_toiMaxIters = 0; + b2_toiRootIters = 0; + b2_toiMaxRootIters = 0; + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - extern int32 b2_toiCalls, b2_toiIters; - extern int32 b2_toiRootIters, b2_toiMaxRootIters; + extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern int32 b2_toiCalls, b2_toiIters; + extern int32 b2_toiRootIters, b2_toiMaxRootIters; - if (b2_gjkCalls > 0) - { - m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", - b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters); - m_textLine += 15; - } + if (b2_gjkCalls > 0) + { + m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", + b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters); + m_textLine += DRAW_STRING_NEW_LINE; + } - if (b2_toiCalls > 0) - { - m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", - b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); - m_textLine += 15; + if (b2_toiCalls > 0) + { + m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", + b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); + m_textLine += DRAW_STRING_NEW_LINE; - m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", - b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters); - m_textLine += 15; - } + m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", + b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters); + m_textLine += DRAW_STRING_NEW_LINE; + } - if (m_stepCount % 60 == 0) - { - Launch(); - } - } + if (m_stepCount % 60 == 0) + { + Launch(); + } + } - static Test* Create() - { - return new BulletTest; - } + static Test* Create() + { + return new BulletTest; + } - b2Body* m_body; - b2Body* m_bullet; - float32 m_x; + b2Body* m_body; + b2Body* m_bullet; + float32 m_x; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h index 223980c185..5a0767984b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h @@ -27,185 +27,185 @@ class Cantilever : public Test { public: - enum - { - e_count = 8 - }; + enum + { + e_count = 8 + }; - Cantilever() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Cantilever() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2WeldJointDef jd; + b2WeldJointDef jd; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } - } + prevBody = body; + } + } - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2WeldJointDef jd; - jd.frequencyHz = 5.0f; - jd.dampingRatio = 0.7f; + b2WeldJointDef jd; + jd.frequencyHz = 5.0f; + jd.dampingRatio = 0.7f; - b2Body* prevBody = ground; - for (int32 i = 0; i < 3; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-14.0f + 2.0f * i, 15.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < 3; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-14.0f + 2.0f * i, 15.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } - } + prevBody = body; + } + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2WeldJointDef jd; + b2WeldJointDef jd; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-4.5f + 1.0f * i, 5.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-4.5f + 1.0f * i, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - if (i > 0) - { - b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - } + if (i > 0) + { + b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + } - prevBody = body; - } - } + prevBody = body; + } + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; - b2WeldJointDef jd; - jd.frequencyHz = 8.0f; - jd.dampingRatio = 0.7f; + b2WeldJointDef jd; + jd.frequencyHz = 8.0f; + jd.dampingRatio = 0.7f; - b2Body* prevBody = ground; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.5f + 1.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.5f + 1.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - if (i > 0) - { - b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); - } + if (i > 0) + { + b2Vec2 anchor(5.0f + 1.0f * i, 10.0f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); + } - prevBody = body; - } - } + prevBody = body; + } + } - for (int32 i = 0; i < 2; ++i) - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); + for (int32 i = 0; i < 2; ++i) + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); - b2PolygonShape shape; - shape.Set(vertices, 3); + b2PolygonShape shape; + shape.Set(vertices, 3); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-8.0f + 8.0f * i, 12.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-8.0f + 8.0f * i, 12.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } - for (int32 i = 0; i < 2; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.5f; + for (int32 i = 0; i < 2; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.5f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 6.0f * i, 10.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 6.0f * i, 10.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - static Test* Create() - { - return new Cantilever; - } + static Test* Create() + { + return new Cantilever; + } - b2Body* m_middle; + b2Body* m_middle; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h index d652f5c3d0..f4d038232f 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h @@ -23,264 +23,264 @@ class Car : public Test { public: - Car() - { - m_hz = 4.0f; - m_zeta = 0.7f; - m_speed = 50.0f; + Car() + { + m_hz = 4.0f; + m_zeta = 0.7f; + m_speed = 50.0f; - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; + b2EdgeShape shape; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 0.0f; - fd.friction = 0.6f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 0.0f; + fd.friction = 0.6f; - shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&fd); + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&fd); - float32 hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; + float32 hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; - float32 x = 20.0f, y1 = 0.0f, dx = 5.0f; + float32 x = 20.0f, y1 = 0.0f, dx = 5.0f; - for (int32 i = 0; i < 10; ++i) - { - float32 y2 = hs[i]; - shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } + for (int32 i = 0; i < 10; ++i) + { + float32 y2 = hs[i]; + shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } - for (int32 i = 0; i < 10; ++i) - { - float32 y2 = hs[i]; - shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)); - ground->CreateFixture(&fd); - y1 = y2; - x += dx; - } + for (int32 i = 0; i < 10; ++i) + { + float32 y2 = hs[i]; + shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)); + ground->CreateFixture(&fd); + y1 = y2; + x += dx; + } - shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 80.0f; - shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + x += 80.0f; + shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 40.0f; - shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); - ground->CreateFixture(&fd); + x += 40.0f; + shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); + ground->CreateFixture(&fd); - x += 20.0f; - shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); - ground->CreateFixture(&fd); + x += 20.0f; + shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); + ground->CreateFixture(&fd); - x += 40.0f; - shape.Set(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); - ground->CreateFixture(&fd); - } + x += 40.0f; + shape.Set(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f)); + ground->CreateFixture(&fd); + } - // Teeter - { - b2BodyDef bd; - bd.position.Set(140.0f, 1.0f); - bd.type = b2_dynamicBody; - b2Body* body = m_world->CreateBody(&bd); + // Teeter + { + b2BodyDef bd; + bd.position.Set(140.0f, 1.0f); + bd.type = b2_dynamicBody; + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape box; - box.SetAsBox(10.0f, 0.25f); - body->CreateFixture(&box, 1.0f); + b2PolygonShape box; + box.SetAsBox(10.0f, 0.25f); + body->CreateFixture(&box, 1.0f); - b2RevoluteJointDef jd; - jd.Initialize(ground, body, body->GetPosition()); - jd.lowerAngle = -8.0f * b2_pi / 180.0f; - jd.upperAngle = 8.0f * b2_pi / 180.0f; - jd.enableLimit = true; - m_world->CreateJoint(&jd); + b2RevoluteJointDef jd; + jd.Initialize(ground, body, body->GetPosition()); + jd.lowerAngle = -8.0f * b2_pi / 180.0f; + jd.upperAngle = 8.0f * b2_pi / 180.0f; + jd.enableLimit = true; + m_world->CreateJoint(&jd); - body->ApplyAngularImpulse(100.0f); - } + body->ApplyAngularImpulse(100.0f, true); + } - // Bridge - { - int32 N = 20; - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.125f); + // Bridge + { + int32 N = 20; + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.6f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.6f; - b2RevoluteJointDef jd; + b2RevoluteJointDef jd; - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(161.0f + 2.0f * i, -0.125f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(161.0f + 2.0f * i, -0.125f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(160.0f + 2.0f * i, -0.125f); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } + prevBody = body; + } - b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); - jd.Initialize(prevBody, ground, anchor); - m_world->CreateJoint(&jd); - } + b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); + jd.Initialize(prevBody, ground, anchor); + m_world->CreateJoint(&jd); + } - // Boxes - { - b2PolygonShape box; - box.SetAsBox(0.5f, 0.5f); + // Boxes + { + b2PolygonShape box; + box.SetAsBox(0.5f, 0.5f); - b2Body* body = NULL; - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2Body* body = NULL; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position.Set(230.0f, 0.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 0.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 1.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 1.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 2.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 2.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 3.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); + bd.position.Set(230.0f, 3.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); - bd.position.Set(230.0f, 4.5f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&box, 0.5f); - } + bd.position.Set(230.0f, 4.5f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&box, 0.5f); + } - // Car - { - b2PolygonShape chassis; - b2Vec2 vertices[8]; - vertices[0].Set(-1.5f, -0.5f); - vertices[1].Set(1.5f, -0.5f); - vertices[2].Set(1.5f, 0.0f); - vertices[3].Set(0.0f, 0.9f); - vertices[4].Set(-1.15f, 0.9f); - vertices[5].Set(-1.5f, 0.2f); - chassis.Set(vertices, 6); + // Car + { + b2PolygonShape chassis; + b2Vec2 vertices[8]; + vertices[0].Set(-1.5f, -0.5f); + vertices[1].Set(1.5f, -0.5f); + vertices[2].Set(1.5f, 0.0f); + vertices[3].Set(0.0f, 0.9f); + vertices[4].Set(-1.15f, 0.9f); + vertices[5].Set(-1.5f, 0.2f); + chassis.Set(vertices, 6); - b2CircleShape circle; - circle.m_radius = 0.4f; + b2CircleShape circle; + circle.m_radius = 0.4f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 1.0f); - m_car = m_world->CreateBody(&bd); - m_car->CreateFixture(&chassis, 1.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 1.0f); + m_car = m_world->CreateBody(&bd); + m_car->CreateFixture(&chassis, 1.0f); - b2FixtureDef fd; - fd.shape = &circle; - fd.density = 1.0f; - fd.friction = 0.9f; + b2FixtureDef fd; + fd.shape = &circle; + fd.density = 1.0f; + fd.friction = 0.9f; - bd.position.Set(-1.0f, 0.35f); - m_wheel1 = m_world->CreateBody(&bd); - m_wheel1->CreateFixture(&fd); + bd.position.Set(-1.0f, 0.35f); + m_wheel1 = m_world->CreateBody(&bd); + m_wheel1->CreateFixture(&fd); - bd.position.Set(1.0f, 0.4f); - m_wheel2 = m_world->CreateBody(&bd); - m_wheel2->CreateFixture(&fd); + bd.position.Set(1.0f, 0.4f); + m_wheel2 = m_world->CreateBody(&bd); + m_wheel2->CreateFixture(&fd); - b2WheelJointDef jd; - b2Vec2 axis(0.0f, 1.0f); + b2WheelJointDef jd; + b2Vec2 axis(0.0f, 1.0f); - jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 20.0f; - jd.enableMotor = true; - jd.frequencyHz = m_hz; - jd.dampingRatio = m_zeta; - m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); + jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 20.0f; + jd.enableMotor = true; + jd.frequencyHz = m_hz; + jd.dampingRatio = m_zeta; + m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd); - jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); - jd.motorSpeed = 0.0f; - jd.maxMotorTorque = 10.0f; - jd.enableMotor = false; - jd.frequencyHz = m_hz; - jd.dampingRatio = m_zeta; - m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); - } - } + jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis); + jd.motorSpeed = 0.0f; + jd.maxMotorTorque = 10.0f; + jd.enableMotor = false; + jd.frequencyHz = m_hz; + jd.dampingRatio = m_zeta; + m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - m_spring1->SetMotorSpeed(m_speed); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_spring1->SetMotorSpeed(m_speed); + break; - case 's': - m_spring1->SetMotorSpeed(0.0f); - break; + case 's': + m_spring1->SetMotorSpeed(0.0f); + break; - case 'd': - m_spring1->SetMotorSpeed(-m_speed); - break; + case 'd': + m_spring1->SetMotorSpeed(-m_speed); + break; - case 'q': - m_hz = b2Max(0.0f, m_hz - 1.0f); - m_spring1->SetSpringFrequencyHz(m_hz); - m_spring2->SetSpringFrequencyHz(m_hz); - break; + case 'q': + m_hz = b2Max(0.0f, m_hz - 1.0f); + m_spring1->SetSpringFrequencyHz(m_hz); + m_spring2->SetSpringFrequencyHz(m_hz); + break; - case 'e': - m_hz += 1.0f; - m_spring1->SetSpringFrequencyHz(m_hz); - m_spring2->SetSpringFrequencyHz(m_hz); - break; - } - } + case 'e': + m_hz += 1.0f; + m_spring1->SetSpringFrequencyHz(m_hz); + m_spring2->SetSpringFrequencyHz(m_hz); + break; + } + } - void Step(Settings* settings) - { - m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "frequency = %g hz, damping ratio = %g", m_hz, m_zeta); - m_textLine += 15; + void Step(Settings* settings) + { + m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, hz down = q, hz up = e"); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "frequency = %g hz, damping ratio = %g", m_hz, m_zeta); + m_textLine += DRAW_STRING_NEW_LINE; - settings->viewCenter.x = m_car->GetPosition().x; - Test::Step(settings); - } + settings->viewCenter.x = m_car->GetPosition().x; + Test::Step(settings); + } - static Test* Create() - { - return new Car; - } + static Test* Create() + { + return new Car; + } - b2Body* m_car; - b2Body* m_wheel1; - b2Body* m_wheel2; + b2Body* m_car; + b2Body* m_wheel1; + b2Body* m_wheel2; - float32 m_hz; - float32 m_zeta; - float32 m_speed; - b2WheelJoint* m_spring1; - b2WheelJoint* m_spring2; + float32 m_hz; + float32 m_zeta; + float32 m_speed; + b2WheelJoint* m_spring1; + b2WheelJoint* m_spring2; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h index bc627178bd..de4414f849 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h @@ -22,53 +22,53 @@ class Chain : public Test { public: - Chain() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Chain() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.6f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.6f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; - b2RevoluteJointDef jd; - jd.collideConnected = false; + b2RevoluteJointDef jd; + jd.collideConnected = false; - const float32 y = 25.0f; - b2Body* prevBody = ground; - for (int32 i = 0; i < 30; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + i, y); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + const float32 y = 25.0f; + b2Body* prevBody = ground; + for (int32 i = 0; i < 30; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + i, y); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); - b2Vec2 anchor(float32(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(float32(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } - } - } + prevBody = body; + } + } + } - static Test* Create() - { - return new Chain; - } + static Test* Create() + { + return new Chain; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h index ee0e6f07bd..541c84f516 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h @@ -25,229 +25,229 @@ class CharacterCollision : public Test { public: - CharacterCollision() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + CharacterCollision() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Collinear edges with no adjacency information. - // This shows the problematic case where a box shape can hit - // an internal vertex. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Collinear edges with no adjacency information. + // This shows the problematic case where a box shape can hit + // an internal vertex. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.Set(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - shape.Set(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.Set(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + shape.Set(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Chain shape - { - b2BodyDef bd; - bd.angle = 0.25f * b2_pi; - b2Body* ground = m_world->CreateBody(&bd); + // Chain shape + { + b2BodyDef bd; + bd.angle = 0.25f * b2_pi; + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[4]; - vs[0].Set(5.0f, 7.0f); - vs[1].Set(6.0f, 8.0f); - vs[2].Set(7.0f, 8.0f); - vs[3].Set(8.0f, 7.0f); - b2ChainShape shape; - shape.CreateChain(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[4]; + vs[0].Set(5.0f, 7.0f); + vs[1].Set(6.0f, 8.0f); + vs[2].Set(7.0f, 8.0f); + vs[3].Set(8.0f, 7.0f); + b2ChainShape shape; + shape.CreateChain(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } - // Square tiles. This shows that adjacency shapes may - // have non-smooth collision. There is no solution - // to this problem. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Square tiles. This shows that adjacency shapes may + // have non-smooth collision. There is no solution + // to this problem. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); - ground->CreateFixture(&shape, 0.0f); - } + b2PolygonShape shape; + shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f); + ground->CreateFixture(&shape, 0.0f); + } - // Square made from an edge loop. Collision should be smooth. - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Square made from an edge loop. Collision should be smooth. + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[4]; - vs[0].Set(-1.0f, 3.0f); - vs[1].Set(1.0f, 3.0f); - vs[2].Set(1.0f, 5.0f); - vs[3].Set(-1.0f, 5.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 4); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[4]; + vs[0].Set(-1.0f, 3.0f); + vs[1].Set(1.0f, 3.0f); + vs[2].Set(1.0f, 5.0f); + vs[3].Set(-1.0f, 5.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 4); + ground->CreateFixture(&shape, 0.0f); + } - // Edge loop. Collision should be smooth. - { - b2BodyDef bd; - bd.position.Set(-10.0f, 4.0f); - b2Body* ground = m_world->CreateBody(&bd); + // Edge loop. Collision should be smooth. + { + b2BodyDef bd; + bd.position.Set(-10.0f, 4.0f); + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 vs[10]; - vs[0].Set(0.0f, 0.0f); - vs[1].Set(6.0f, 0.0f); - vs[2].Set(6.0f, 2.0f); - vs[3].Set(4.0f, 1.0f); - vs[4].Set(2.0f, 2.0f); - vs[5].Set(0.0f, 2.0f); - vs[6].Set(-2.0f, 2.0f); - vs[7].Set(-4.0f, 3.0f); - vs[8].Set(-6.0f, 2.0f); - vs[9].Set(-6.0f, 0.0f); - b2ChainShape shape; - shape.CreateLoop(vs, 10); - ground->CreateFixture(&shape, 0.0f); - } + b2Vec2 vs[10]; + vs[0].Set(0.0f, 0.0f); + vs[1].Set(6.0f, 0.0f); + vs[2].Set(6.0f, 2.0f); + vs[3].Set(4.0f, 1.0f); + vs[4].Set(2.0f, 2.0f); + vs[5].Set(0.0f, 2.0f); + vs[6].Set(-2.0f, 2.0f); + vs[7].Set(-4.0f, 3.0f); + vs[8].Set(-6.0f, 2.0f); + vs[9].Set(-6.0f, 0.0f); + b2ChainShape shape; + shape.CreateLoop(vs, 10); + ground->CreateFixture(&shape, 0.0f); + } - // Square character 1 - { - b2BodyDef bd; - bd.position.Set(-3.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Square character 1 + { + b2BodyDef bd; + bd.position.Set(-3.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Square character 2 - { - b2BodyDef bd; - bd.position.Set(-5.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Square character 2 + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Hexagon character - { - b2BodyDef bd; - bd.position.Set(-5.0f, 8.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Hexagon character + { + b2BodyDef bd; + bd.position.Set(-5.0f, 8.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - float32 angle = 0.0f; - float32 delta = b2_pi / 3.0f; - b2Vec2 vertices[6]; - for (int32 i = 0; i < 6; ++i) - { - vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); - angle += delta; - } + float32 angle = 0.0f; + float32 delta = b2_pi / 3.0f; + b2Vec2 vertices[6]; + for (int32 i = 0; i < 6; ++i) + { + vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle)); + angle += delta; + } - b2PolygonShape shape; - shape.Set(vertices, 6); + b2PolygonShape shape; + shape.Set(vertices, 6); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(3.0f, 5.0f); - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.allowSleep = false; + // Circle character + { + b2BodyDef bd; + bd.position.Set(3.0f, 5.0f); + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = 0.5f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - body->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + body->CreateFixture(&fd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(-7.0f, 6.0f); - bd.type = b2_dynamicBody; - bd.allowSleep = false; + // Circle character + { + b2BodyDef bd; + bd.position.Set(-7.0f, 6.0f); + bd.type = b2_dynamicBody; + bd.allowSleep = false; - m_character = m_world->CreateBody(&bd); + m_character = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.25f; + b2CircleShape shape; + shape.m_radius = 0.25f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 1.0f; - m_character->CreateFixture(&fd); - } - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 1.0f; + m_character->CreateFixture(&fd); + } + } - void Step(Settings* settings) - { - b2Vec2 v = m_character->GetLinearVelocity(); - v.x = -5.0f; - m_character->SetLinearVelocity(v); + void Step(Settings* settings) + { + b2Vec2 v = m_character->GetLinearVelocity(); + v.x = -5.0f; + m_character->SetLinearVelocity(v); - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "This tests various character collision shapes."); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); - m_textLine += 15; - } + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "This tests various character collision shapes."); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Limitation: square and hexagon can snag on aligned boxes."); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Feature: edge chains have smooth collision inside and out."); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new CharacterCollision; - } + static Test* Create() + { + return new CharacterCollision; + } - b2Body* m_character; + b2Body* m_character; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h index 41601098bd..8a11dc195f 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h @@ -25,7 +25,7 @@ // The 3 small ones always collide. // The 3 large ones never collide. // The boxes don't collide with triangles (except if both are small). -const int16 k_smallGroup = 1; +const int16 k_smallGroup = 1; const int16 k_largeGroup = -1; const uint16 k_defaultCategory = 0x0001; @@ -40,137 +40,138 @@ const uint16 k_circleMask = 0xFFFF; class CollisionFiltering : public Test { public: - CollisionFiltering() - { - // Ground body - { - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + CollisionFiltering() + { + // Ground body + { + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2FixtureDef sd; - sd.shape = &shape; - sd.friction = 0.3f; + b2FixtureDef sd; + sd.shape = &shape; + sd.friction = 0.3f; - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); - b2PolygonShape polygon; - polygon.Set(vertices, 3); + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); + b2PolygonShape polygon; + polygon.Set(vertices, 3); - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; - triangleShapeDef.filter.groupIndex = k_smallGroup; - triangleShapeDef.filter.categoryBits = k_triangleCategory; - triangleShapeDef.filter.maskBits = k_triangleMask; + triangleShapeDef.filter.groupIndex = k_smallGroup; + triangleShapeDef.filter.categoryBits = k_triangleCategory; + triangleShapeDef.filter.maskBits = k_triangleMask; - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(-5.0f, 2.0f); + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(-5.0f, 2.0f); - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); - triangleShapeDef.filter.groupIndex = k_largeGroup; - triangleBodyDef.position.Set(-5.0f, 6.0f); - triangleBodyDef.fixedRotation = true; // look at me! + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); + triangleShapeDef.filter.groupIndex = k_largeGroup; + triangleBodyDef.position.Set(-5.0f, 6.0f); + triangleBodyDef.fixedRotation = true; // look at me! - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-5.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape p; - p.SetAsBox(0.5f, 1.0f); - body->CreateFixture(&p, 1.0f); + b2PolygonShape p; + p.SetAsBox(0.5f, 1.0f); + body->CreateFixture(&p, 1.0f); - b2PrismaticJointDef jd; - jd.bodyA = body2; - jd.bodyB = body; - jd.enableLimit = true; - jd.localAnchorA.Set(0.0f, 4.0f); - jd.localAnchorB.SetZero(); - jd.localAxisA.Set(0.0f, 1.0f); - jd.lowerTranslation = -1.0f; - jd.upperTranslation = 1.0f; + b2PrismaticJointDef jd; + jd.bodyA = body2; + jd.bodyB = body; + jd.enableLimit = true; + jd.localAnchorA.Set(0.0f, 4.0f); + jd.localAnchorB.SetZero(); + jd.localAxisA.Set(0.0f, 1.0f); + jd.lowerTranslation = -1.0f; + jd.upperTranslation = 1.0f; - m_world->CreateJoint(&jd); - } + m_world->CreateJoint(&jd); + } - // Small box - polygon.SetAsBox(1.0f, 0.5f); - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; - boxShapeDef.restitution = 0.1f; + // Small box + polygon.SetAsBox(1.0f, 0.5f); + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; + boxShapeDef.restitution = 0.1f; - boxShapeDef.filter.groupIndex = k_smallGroup; - boxShapeDef.filter.categoryBits = k_boxCategory; - boxShapeDef.filter.maskBits = k_boxMask; + boxShapeDef.filter.groupIndex = k_smallGroup; + boxShapeDef.filter.categoryBits = k_boxCategory; + boxShapeDef.filter.maskBits = k_boxMask; - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(0.0f, 2.0f); + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(0.0f, 2.0f); - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxShapeDef.filter.groupIndex = k_largeGroup; - boxBodyDef.position.Set(0.0f, 6.0f); + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxShapeDef.filter.groupIndex = k_largeGroup; + boxBodyDef.position.Set(0.0f, 6.0f); - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; - circleShapeDef.filter.groupIndex = k_smallGroup; - circleShapeDef.filter.categoryBits = k_circleCategory; - circleShapeDef.filter.maskBits = k_circleMask; + circleShapeDef.filter.groupIndex = k_smallGroup; + circleShapeDef.filter.categoryBits = k_circleCategory; + circleShapeDef.filter.maskBits = k_circleMask; - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(5.0f, 2.0f); - - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(5.0f, 2.0f); + + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); - // Large circle - circle.m_radius *= 2.0f; - circleShapeDef.filter.groupIndex = k_largeGroup; - circleBodyDef.position.Set(5.0f, 6.0f); + // Large circle + circle.m_radius *= 2.0f; + circleShapeDef.filter.groupIndex = k_largeGroup; + circleBodyDef.position.Set(5.0f, 6.0f); - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } - static Test* Create() - { - return new CollisionFiltering; - } + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } + + static Test* Create() + { + return new CollisionFiltering; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h index 61cee0ea9d..e969d98082 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h @@ -26,163 +26,163 @@ class CollisionProcessing : public Test { public: - CollisionProcessing() - { - // Ground body - { - b2EdgeShape shape; - shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + CollisionProcessing() + { + // Ground body + { + b2EdgeShape shape; + shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - b2FixtureDef sd; - sd.shape = &shape;; + b2FixtureDef sd; + sd.shape = &shape;; - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&sd); - } + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&sd); + } - float32 xLo = -5.0f, xHi = 5.0f; - float32 yLo = 2.0f, yHi = 35.0f; + float32 xLo = -5.0f, xHi = 5.0f; + float32 yLo = 2.0f, yHi = 35.0f; - // Small triangle - b2Vec2 vertices[3]; - vertices[0].Set(-1.0f, 0.0f); - vertices[1].Set(1.0f, 0.0f); - vertices[2].Set(0.0f, 2.0f); + // Small triangle + b2Vec2 vertices[3]; + vertices[0].Set(-1.0f, 0.0f); + vertices[1].Set(1.0f, 0.0f); + vertices[2].Set(0.0f, 2.0f); - b2PolygonShape polygon; - polygon.Set(vertices, 3); + b2PolygonShape polygon; + polygon.Set(vertices, 3); - b2FixtureDef triangleShapeDef; - triangleShapeDef.shape = &polygon; - triangleShapeDef.density = 1.0f; + b2FixtureDef triangleShapeDef; + triangleShapeDef.shape = &polygon; + triangleShapeDef.density = 1.0f; - b2BodyDef triangleBodyDef; - triangleBodyDef.type = b2_dynamicBody; - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + b2BodyDef triangleBodyDef; + triangleBodyDef.type = b2_dynamicBody; + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body1 = m_world->CreateBody(&triangleBodyDef); - body1->CreateFixture(&triangleShapeDef); + b2Body* body1 = m_world->CreateBody(&triangleBodyDef); + body1->CreateFixture(&triangleShapeDef); - // Large triangle (recycle definitions) - vertices[0] *= 2.0f; - vertices[1] *= 2.0f; - vertices[2] *= 2.0f; - polygon.Set(vertices, 3); + // Large triangle (recycle definitions) + vertices[0] *= 2.0f; + vertices[1] *= 2.0f; + vertices[2] *= 2.0f; + polygon.Set(vertices, 3); - triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body2 = m_world->CreateBody(&triangleBodyDef); - body2->CreateFixture(&triangleShapeDef); - - // Small box - polygon.SetAsBox(1.0f, 0.5f); + b2Body* body2 = m_world->CreateBody(&triangleBodyDef); + body2->CreateFixture(&triangleShapeDef); + + // Small box + polygon.SetAsBox(1.0f, 0.5f); - b2FixtureDef boxShapeDef; - boxShapeDef.shape = &polygon; - boxShapeDef.density = 1.0f; + b2FixtureDef boxShapeDef; + boxShapeDef.shape = &polygon; + boxShapeDef.density = 1.0f; - b2BodyDef boxBodyDef; - boxBodyDef.type = b2_dynamicBody; - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + b2BodyDef boxBodyDef; + boxBodyDef.type = b2_dynamicBody; + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body3 = m_world->CreateBody(&boxBodyDef); - body3->CreateFixture(&boxShapeDef); + b2Body* body3 = m_world->CreateBody(&boxBodyDef); + body3->CreateFixture(&boxShapeDef); - // Large box (recycle definitions) - polygon.SetAsBox(2.0f, 1.0f); - boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - - b2Body* body4 = m_world->CreateBody(&boxBodyDef); - body4->CreateFixture(&boxShapeDef); + // Large box (recycle definitions) + polygon.SetAsBox(2.0f, 1.0f); + boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + + b2Body* body4 = m_world->CreateBody(&boxBodyDef); + body4->CreateFixture(&boxShapeDef); - // Small circle - b2CircleShape circle; - circle.m_radius = 1.0f; + // Small circle + b2CircleShape circle; + circle.m_radius = 1.0f; - b2FixtureDef circleShapeDef; - circleShapeDef.shape = &circle; - circleShapeDef.density = 1.0f; + b2FixtureDef circleShapeDef; + circleShapeDef.shape = &circle; + circleShapeDef.density = 1.0f; - b2BodyDef circleBodyDef; - circleBodyDef.type = b2_dynamicBody; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + b2BodyDef circleBodyDef; + circleBodyDef.type = b2_dynamicBody; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body5 = m_world->CreateBody(&circleBodyDef); - body5->CreateFixture(&circleShapeDef); + b2Body* body5 = m_world->CreateBody(&circleBodyDef); + body5->CreateFixture(&circleShapeDef); - // Large circle - circle.m_radius *= 2.0f; - circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); + // Large circle + circle.m_radius *= 2.0f; + circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi)); - b2Body* body6 = m_world->CreateBody(&circleBodyDef); - body6->CreateFixture(&circleShapeDef); - } + b2Body* body6 = m_world->CreateBody(&circleBodyDef); + body6->CreateFixture(&circleShapeDef); + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - // We are going to destroy some bodies according to contact - // points. We must buffer the bodies that should be destroyed - // because they may belong to multiple contact points. - const int32 k_maxNuke = 6; - b2Body* nuke[k_maxNuke]; - int32 nukeCount = 0; + // We are going to destroy some bodies according to contact + // points. We must buffer the bodies that should be destroyed + // because they may belong to multiple contact points. + const int32 k_maxNuke = 6; + b2Body* nuke[k_maxNuke]; + int32 nukeCount = 0; - // Traverse the contact results. Destroy bodies that - // are touching heavier bodies. - for (int32 i = 0; i < m_pointCount; ++i) - { - ContactPoint* point = m_points + i; + // Traverse the contact results. Destroy bodies that + // are touching heavier bodies. + for (int32 i = 0; i < m_pointCount; ++i) + { + ContactPoint* point = m_points + i; - b2Body* body1 = point->fixtureA->GetBody(); - b2Body* body2 = point->fixtureB->GetBody(); - float32 mass1 = body1->GetMass(); - float32 mass2 = body2->GetMass(); + b2Body* body1 = point->fixtureA->GetBody(); + b2Body* body2 = point->fixtureB->GetBody(); + float32 mass1 = body1->GetMass(); + float32 mass2 = body2->GetMass(); - if (mass1 > 0.0f && mass2 > 0.0f) - { - if (mass2 > mass1) - { - nuke[nukeCount++] = body1; - } - else - { - nuke[nukeCount++] = body2; - } + if (mass1 > 0.0f && mass2 > 0.0f) + { + if (mass2 > mass1) + { + nuke[nukeCount++] = body1; + } + else + { + nuke[nukeCount++] = body2; + } - if (nukeCount == k_maxNuke) - { - break; - } - } - } + if (nukeCount == k_maxNuke) + { + break; + } + } + } - // Sort the nuke array to group duplicates. - std::sort(nuke, nuke + nukeCount); + // Sort the nuke array to group duplicates. + std::sort(nuke, nuke + nukeCount); - // Destroy the bodies, skipping duplicates. - int32 i = 0; - while (i < k_maxNuke && i < nukeCount) - { - b2Body* b = nuke[i++]; - while (i < k_maxNuke && i < nukeCount && nuke[i] == b) - { - ++i; - } + // Destroy the bodies, skipping duplicates. + int32 i = 0; + while (i < nukeCount) + { + b2Body* b = nuke[i++]; + while (i < nukeCount && nuke[i] == b) + { + ++i; + } - if (b != m_bomb) - { - m_world->DestroyBody(b); - } - } - } + if (b != m_bomb) + { + m_world->DestroyBody(b); + } + } + } - static Test* Create() - { - return new CollisionProcessing; - } + static Test* Create() + { + return new CollisionProcessing; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h index 9a5ec74018..bdba8a60d5 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h @@ -23,121 +23,121 @@ class CompoundShapes : public Test { public: - CompoundShapes() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); + CompoundShapes() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + b2EdgeShape shape; + shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - body->CreateFixture(&shape, 0.0f); - } + body->CreateFixture(&shape, 0.0f); + } - { - b2CircleShape circle1; - circle1.m_radius = 0.5f; - circle1.m_p.Set(-0.5f, 0.5f); + { + b2CircleShape circle1; + circle1.m_radius = 0.5f; + circle1.m_p.Set(-0.5f, 0.5f); - b2CircleShape circle2; - circle2.m_radius = 0.5f; - circle2.m_p.Set(0.5f, 0.5f); + b2CircleShape circle2; + circle2.m_radius = 0.5f; + circle2.m_p.Set(0.5f, 0.5f); - for (int i = 0; i < 10; ++i) - { - float32 x = RandomFloat(-0.1f, 0.1f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(x + 5.0f, 1.05f + 2.5f * i); - bd.angle = RandomFloat(-b2_pi, b2_pi); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&circle1, 2.0f); - body->CreateFixture(&circle2, 0.0f); - } - } + for (int i = 0; i < 10; ++i) + { + float32 x = RandomFloat(-0.1f, 0.1f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(x + 5.0f, 1.05f + 2.5f * i); + bd.angle = RandomFloat(-b2_pi, b2_pi); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&circle1, 2.0f); + body->CreateFixture(&circle2, 0.0f); + } + } - { - b2PolygonShape polygon1; - polygon1.SetAsBox(0.25f, 0.5f); + { + b2PolygonShape polygon1; + polygon1.SetAsBox(0.25f, 0.5f); - b2PolygonShape polygon2; - polygon2.SetAsBox(0.25f, 0.5f, b2Vec2(0.0f, -0.5f), 0.5f * b2_pi); + b2PolygonShape polygon2; + polygon2.SetAsBox(0.25f, 0.5f, b2Vec2(0.0f, -0.5f), 0.5f * b2_pi); - for (int i = 0; i < 10; ++i) - { - float32 x = RandomFloat(-0.1f, 0.1f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(x - 5.0f, 1.05f + 2.5f * i); - bd.angle = RandomFloat(-b2_pi, b2_pi); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&polygon1, 2.0f); - body->CreateFixture(&polygon2, 2.0f); - } - } + for (int i = 0; i < 10; ++i) + { + float32 x = RandomFloat(-0.1f, 0.1f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(x - 5.0f, 1.05f + 2.5f * i); + bd.angle = RandomFloat(-b2_pi, b2_pi); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&polygon1, 2.0f); + body->CreateFixture(&polygon2, 2.0f); + } + } - { - b2Transform xf1; - xf1.q.Set(0.3524f * b2_pi); - xf1.p = xf1.q.GetXAxis(); + { + b2Transform xf1; + xf1.q.Set(0.3524f * b2_pi); + xf1.p = xf1.q.GetXAxis(); - b2Vec2 vertices[3]; + b2Vec2 vertices[3]; - b2PolygonShape triangle1; - vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); - triangle1.Set(vertices, 3); + b2PolygonShape triangle1; + vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); + triangle1.Set(vertices, 3); - b2Transform xf2; - xf2.q.Set(-0.3524f * b2_pi); - xf2.p = -xf2.q.GetXAxis(); + b2Transform xf2; + xf2.q.Set(-0.3524f * b2_pi); + xf2.p = -xf2.q.GetXAxis(); - b2PolygonShape triangle2; - vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); - vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); - vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); - triangle2.Set(vertices, 3); + b2PolygonShape triangle2; + vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); + vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); + vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); + triangle2.Set(vertices, 3); - for (int32 i = 0; i < 10; ++i) - { - float32 x = RandomFloat(-0.1f, 0.1f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(x, 2.05f + 2.5f * i); - bd.angle = 0.0f; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&triangle1, 2.0f); - body->CreateFixture(&triangle2, 2.0f); - } - } + for (int32 i = 0; i < 10; ++i) + { + float32 x = RandomFloat(-0.1f, 0.1f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(x, 2.05f + 2.5f * i); + bd.angle = 0.0f; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&triangle1, 2.0f); + body->CreateFixture(&triangle2, 2.0f); + } + } - { - b2PolygonShape bottom; - bottom.SetAsBox( 1.5f, 0.15f ); + { + b2PolygonShape bottom; + bottom.SetAsBox( 1.5f, 0.15f ); - b2PolygonShape left; - left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.2f); + b2PolygonShape left; + left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.2f); - b2PolygonShape right; - right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0.2f); + b2PolygonShape right; + right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0.2f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set( 0.0f, 2.0f ); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&bottom, 4.0f); - body->CreateFixture(&left, 4.0f); - body->CreateFixture(&right, 4.0f); - } - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set( 0.0f, 2.0f ); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&bottom, 4.0f); + body->CreateFixture(&left, 4.0f); + body->CreateFixture(&right, 4.0f); + } + } - static Test* Create() - { - return new CompoundShapes; - } + static Test* Create() + { + return new CompoundShapes; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h index 5b5ed90dc0..638b2b8c7f 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h @@ -23,145 +23,145 @@ class Confined : public Test { public: - enum - { - e_columnCount = 0, - e_rowCount = 0 - }; + enum + { + e_columnCount = 0, + e_rowCount = 0 + }; - Confined() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + Confined() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; + b2EdgeShape shape; - // Floor - shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + // Floor + shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - // Left wall - shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); + // Left wall + shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); - // Right wall - shape.Set(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); + // Right wall + shape.Set(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); - // Roof - shape.Set(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } + // Roof + shape.Set(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } - float32 radius = 0.5f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; + float32 radius = 0.5f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.1f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.1f; - for (int32 j = 0; j < e_columnCount; ++j) - { - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); - b2Body* body = m_world->CreateBody(&bd); + for (int32 j = 0; j < e_columnCount; ++j) + { + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); + b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + body->CreateFixture(&fd); + } + } - m_world->SetGravity(b2Vec2(0.0f, 0.0f)); - } + m_world->SetGravity(b2Vec2(0.0f, 0.0f)); + } - void CreateCircle() - { - float32 radius = 2.0f; - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = radius; + void CreateCircle() + { + float32 radius = 2.0f; + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = radius; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.0f; - b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = p; - //bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = p; + //bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } + body->CreateFixture(&fd); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'c': - CreateCircle(); - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case 'c': + CreateCircle(); + break; + } + } - void Step(Settings* settings) - { - //bool sleeping = true; - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } + void Step(Settings* settings) + { + bool sleeping = true; + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } - //if (b->IsAwake()) - //{ - // sleeping = false; - //} - } + if (b->IsAwake()) + { + sleeping = false; + } + } - if (m_stepCount == 180) - { - m_stepCount += 0; - } + if (m_stepCount == 180) + { + m_stepCount += 0; + } - //if (sleeping) - //{ - // CreateCircle(); - //} + //if (sleeping) + //{ + // CreateCircle(); + //} - Test::Step(settings); + Test::Step(settings); - for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) - { - if (b->GetType() != b2_dynamicBody) - { - continue; - } + for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) + { + if (b->GetType() != b2_dynamicBody) + { + continue; + } - b2Vec2 p = b->GetPosition(); - if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) - { - p.x += 0.0; - } - } + b2Vec2 p = b->GetPosition(); + if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.y) + { + p.x += 0.0f; + } + } - m_debugDraw.DrawString(5, m_textLine, "Press 'c' to create a circle."); - m_textLine += 15; - } + m_debugDraw.DrawString(5, m_textLine, "Press 'c' to create a circle."); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Confined; - } + static Test* Create() + { + return new Confined; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h index 2a845b2c65..7165aac374 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h @@ -23,115 +23,135 @@ class ContinuousTest : public Test { public: - ContinuousTest() - { - { - b2BodyDef bd; - bd.position.Set(0.0f, 0.0f); - b2Body* body = m_world->CreateBody(&bd); + ContinuousTest() + { + { + b2BodyDef bd; + bd.position.Set(0.0f, 0.0f); + b2Body* body = m_world->CreateBody(&bd); - b2EdgeShape edge; + b2EdgeShape edge; - edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); - body->CreateFixture(&edge, 0.0f); + edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); + body->CreateFixture(&edge, 0.0f); - b2PolygonShape shape; - shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); - body->CreateFixture(&shape, 0.0f); - } + b2PolygonShape shape; + shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); + body->CreateFixture(&shape, 0.0f); + } #if 1 - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 20.0f); - //bd.angle = 0.1f; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 20.0f); + //bd.angle = 0.1f; - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.1f); + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.1f); - m_body = m_world->CreateBody(&bd); - m_body->CreateFixture(&shape, 1.0f); + m_body = m_world->CreateBody(&bd); + m_body->CreateFixture(&shape, 1.0f); - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - //m_angularVelocity = 46.661274f; - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + //m_angularVelocity = 46.661274f; + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } #else - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 2.0f); - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 2.0f); + b2Body* body = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_p.SetZero(); - shape.m_radius = 0.5f; - body->CreateFixture(&shape, 1.0f); + b2CircleShape shape; + shape.m_p.SetZero(); + shape.m_radius = 0.5f; + body->CreateFixture(&shape, 1.0f); - bd.bullet = true; - bd.position.Set(0.0f, 10.0f); - body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - } + bd.bullet = true; + bd.position.Set(0.0f, 10.0f); + body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + } #endif - } - void Launch() - { - m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); - m_angularVelocity = RandomFloat(-50.0f, 50.0f); - m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); - m_body->SetAngularVelocity(m_angularVelocity); - } + extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern int32 b2_toiCalls, b2_toiIters; + extern int32 b2_toiRootIters, b2_toiMaxRootIters; + extern float32 b2_toiTime, b2_toiMaxTime; - void Step(Settings* settings) - { - if (m_stepCount == 12) - { - m_stepCount += 0; - } + b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; + b2_toiCalls = 0; b2_toiIters = 0; + b2_toiRootIters = 0; b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; + } - Test::Step(settings); + void Launch() + { + extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + extern int32 b2_toiCalls, b2_toiIters; + extern int32 b2_toiRootIters, b2_toiMaxRootIters; + extern float32 b2_toiTime, b2_toiMaxTime; - extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; + b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; + b2_toiCalls = 0; b2_toiIters = 0; + b2_toiRootIters = 0; b2_toiMaxRootIters = 0; + b2_toiTime = 0.0f; b2_toiMaxTime = 0.0f; - if (b2_gjkCalls > 0) - { - m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", - b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters); - m_textLine += 15; - } + m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); + m_angularVelocity = RandomFloat(-50.0f, 50.0f); + m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); + m_body->SetAngularVelocity(m_angularVelocity); + } - extern int32 b2_toiCalls, b2_toiIters; - extern int32 b2_toiRootIters, b2_toiMaxRootIters; + void Step(Settings* settings) + { + Test::Step(settings); - if (b2_toiCalls > 0) - { - m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", - b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); - m_textLine += 15; - - m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", - b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters); - m_textLine += 15; - } + extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - if (m_stepCount % 60 == 0) - { - //Launch(); - } - } + if (b2_gjkCalls > 0) + { + m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", + b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new ContinuousTest; - } + extern int32 b2_toiCalls, b2_toiIters; + extern int32 b2_toiRootIters, b2_toiMaxRootIters; + extern float32 b2_toiTime, b2_toiMaxTime; - b2Body* m_body; - float32 m_angularVelocity; + if (b2_toiCalls > 0) + { + m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave [max] toi iters = %3.1f [%d]", + b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); + m_textLine += DRAW_STRING_NEW_LINE; + + m_debugDraw.DrawString(5, m_textLine, "ave [max] toi root iters = %3.1f [%d]", + b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters); + m_textLine += DRAW_STRING_NEW_LINE; + + m_debugDraw.DrawString(5, m_textLine, "ave [max] toi time = %.1f [%.1f] (microseconds)", + 1000.0f * b2_toiTime / float32(b2_toiCalls), 1000.0f * b2_toiMaxTime); + m_textLine += DRAW_STRING_NEW_LINE; + } + + if (m_stepCount % 60 == 0) + { + //Launch(); + } + } + + static Test* Create() + { + return new ContinuousTest; + } + + b2Body* m_body; + float32 m_angularVelocity; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h new file mode 100644 index 0000000000..fc5742892b --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h @@ -0,0 +1,116 @@ +/* +* Copyright (c) 2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef CONVEX_HULL_H +#define CONVEX_HULL_H + +class ConvexHull : public Test +{ +public: + enum + { + e_count = b2_maxPolygonVertices + }; + + ConvexHull() + { + Generate(); + m_auto = false; + } + + void Generate() + { + b2Vec2 lowerBound(-8.0f, -8.0f); + b2Vec2 upperBound(8.0f, 8.0f); + + for (int32 i = 0; i < e_count; ++i) + { + float32 x = 10.0f * RandomFloat(); + float32 y = 10.0f * RandomFloat(); + + // Clamp onto a square to help create collinearities. + // This will stress the convex hull algorithm. + b2Vec2 v(x, y); + v = b2Clamp(v, lowerBound, upperBound); + m_points[i] = v; + } + + m_count = e_count; + + m_points[0].Set( -1.70082211f, -1.43221712f ); + m_points[1].Set( 0.5f, -0.5f ); + m_points[2].Set( 0.104992867f, 0.97400856f ); + m_points[3].Set( -0.658002853f, 0.926608086f ); + m_points[4].Set( -0.994554818f, 0.165337861f ); + m_count = 5; + } + + static Test* Create() + { + return new ConvexHull; + } + + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_auto = !m_auto; + break; + + case 'g': + Generate(); + break; + } + } + + void Step(Settings* settings) + { + Test::Step(settings); + + b2PolygonShape shape; + shape.Set(m_points, m_count); + + m_debugDraw.DrawString(5, m_textLine, "Press g to generate a new random convex hull"); + m_textLine += DRAW_STRING_NEW_LINE; + + m_debugDraw.DrawPolygon(shape.m_vertices, shape.m_count, b2Color(0.9f, 0.9f, 0.9f)); + + for (int32 i = 0; i < m_count; ++i) + { + m_debugDraw.DrawPoint(m_points[i], 2.0f, b2Color(0.9f, 0.5f, 0.5f)); + //m_debugDraw.DrawString(m_points[i] + b2Vec2(0.05f, 0.05f), "%d", i); + } + + if (shape.Validate() == false) + { + m_textLine += 0; + } + + if (m_auto) + { + Generate(); + } + } + + b2Vec2 m_points[b2_maxPolygonVertices]; + int32 m_count; + bool m_auto; +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h new file mode 100644 index 0000000000..01ddc94043 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2011 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef CONVEYOR_BELT_H +#define CONVEYOR_BELT_H + +class ConveyorBelt : public Test +{ +public: + + ConveyorBelt() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } + + // Platform + { + b2BodyDef bd; + bd.position.Set(-5.0f, 5.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(10.0f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.8f; + m_platform = body->CreateFixture(&fd); + } + + // Boxes + for (int32 i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 2.0f * i, 7.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); + body->CreateFixture(&shape, 20.0f); + } + } + + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + Test::PreSolve(contact, oldManifold); + + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); + + if (fixtureA == m_platform) + { + contact->SetTangentSpeed(5.0f); + } + + if (fixtureB == m_platform) + { + contact->SetTangentSpeed(-5.0f); + } + } + + void Step(Settings* settings) + { + Test::Step(settings); + } + + static Test* Create() + { + return new ConveyorBelt; + } + + b2Fixture* m_platform; +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h index 4db52ca31f..de8c720a3d 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h @@ -22,114 +22,114 @@ class DistanceTest : public Test { public: - DistanceTest() - { - { - m_transformA.SetIdentity(); - m_transformA.p.Set(0.0f, -0.2f); - m_polygonA.SetAsBox(10.0f, 0.2f); - } + DistanceTest() + { + { + m_transformA.SetIdentity(); + m_transformA.p.Set(0.0f, -0.2f); + m_polygonA.SetAsBox(10.0f, 0.2f); + } - { - m_positionB.Set(12.017401f, 0.13678508f); - m_angleB = -0.0109265f; - m_transformB.Set(m_positionB, m_angleB); + { + m_positionB.Set(12.017401f, 0.13678508f); + m_angleB = -0.0109265f; + m_transformB.Set(m_positionB, m_angleB); - m_polygonB.SetAsBox(2.0f, 0.1f); - } - } + m_polygonB.SetAsBox(2.0f, 0.1f); + } + } - static Test* Create() - { - return new DistanceTest; - } + static Test* Create() + { + return new DistanceTest; + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - b2DistanceInput input; - input.proxyA.Set(&m_polygonA, 0); - input.proxyB.Set(&m_polygonB, 0); - input.transformA = m_transformA; - input.transformB = m_transformB; - input.useRadii = true; - b2SimplexCache cache; - cache.count = 0; - b2DistanceOutput output; - b2Distance(&output, &cache, &input); + b2DistanceInput input; + input.proxyA.Set(&m_polygonA, 0); + input.proxyB.Set(&m_polygonB, 0); + input.transformA = m_transformA; + input.transformB = m_transformB; + input.useRadii = true; + b2SimplexCache cache; + cache.count = 0; + b2DistanceOutput output; + b2Distance(&output, &cache, &input); - m_debugDraw.DrawString(5, m_textLine, "distance = %g", output.distance); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "distance = %g", output.distance); + m_textLine += DRAW_STRING_NEW_LINE; - m_debugDraw.DrawString(5, m_textLine, "iterations = %d", output.iterations); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "iterations = %d", output.iterations); + m_textLine += DRAW_STRING_NEW_LINE; - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount, color); + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + m_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, color); - } + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } - b2Vec2 x1 = output.pointA; - b2Vec2 x2 = output.pointB; + b2Vec2 x1 = output.pointA; + b2Vec2 x2 = output.pointB; - b2Color c1(1.0f, 0.0f, 0.0f); - m_debugDraw.DrawPoint(x1, 4.0f, c1); + b2Color c1(1.0f, 0.0f, 0.0f); + m_debugDraw.DrawPoint(x1, 4.0f, c1); - b2Color c2(1.0f, 1.0f, 0.0f); - m_debugDraw.DrawPoint(x2, 4.0f, c2); - } + b2Color c2(1.0f, 1.0f, 0.0f); + m_debugDraw.DrawPoint(x2, 4.0f, c2); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - m_positionB.x -= 0.1f; - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_positionB.x -= 0.1f; + break; - case 'd': - m_positionB.x += 0.1f; - break; + case 'd': + m_positionB.x += 0.1f; + break; - case 's': - m_positionB.y -= 0.1f; - break; + case 's': + m_positionB.y -= 0.1f; + break; - case 'w': - m_positionB.y += 0.1f; - break; + case 'w': + m_positionB.y += 0.1f; + break; - case 'q': - m_angleB += 0.1f * b2_pi; - break; + case 'q': + m_angleB += 0.1f * b2_pi; + break; - case 'e': - m_angleB -= 0.1f * b2_pi; - break; - } + case 'e': + m_angleB -= 0.1f * b2_pi; + break; + } - m_transformB.Set(m_positionB, m_angleB); - } + m_transformB.Set(m_positionB, m_angleB); + } - b2Vec2 m_positionB; - float32 m_angleB; + b2Vec2 m_positionB; + float32 m_angleB; - b2Transform m_transformA; - b2Transform m_transformB; - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; + b2Transform m_transformA; + b2Transform m_transformB; + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h index 8d4e564c4a..2d9b310cf3 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h @@ -23,193 +23,193 @@ class Dominos : public Test { public: - Dominos() - { - b2Body* b1; - { - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + Dominos() + { + b2Body* b1; + { + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2BodyDef bd; - b1 = m_world->CreateBody(&bd); - b1->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + b1 = m_world->CreateBody(&bd); + b1->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.25f); + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.25f); - b2BodyDef bd; - bd.position.Set(-1.5f, 10.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(-1.5f, 10.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.1f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.1f; - for (int i = 0; i < 10; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-6.0f + 1.0f * i, 11.25f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); - } - } + for (int i = 0; i < 10; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-6.0f + 1.0f * i, 11.25f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&fd); + } + } - { - b2PolygonShape shape; - shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); + { + b2PolygonShape shape; + shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f); - b2BodyDef bd; - bd.position.Set(1.0f, 6.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(1.0f, 6.0f); + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - b2Body* b2; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.5f); + b2Body* b2; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.5f); - b2BodyDef bd; - bd.position.Set(-7.0f, 4.0f); - b2 = m_world->CreateBody(&bd); - b2->CreateFixture(&shape, 0.0f); - } + b2BodyDef bd; + bd.position.Set(-7.0f, 4.0f); + b2 = m_world->CreateBody(&bd); + b2->CreateFixture(&shape, 0.0f); + } - b2Body* b3; - { - b2PolygonShape shape; - shape.SetAsBox(6.0f, 0.125f); + b2Body* b3; + { + b2PolygonShape shape; + shape.SetAsBox(6.0f, 0.125f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-0.9f, 1.0f); - bd.angle = -0.15f; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-0.9f, 1.0f); + bd.angle = -0.15f; - b3 = m_world->CreateBody(&bd); - b3->CreateFixture(&shape, 10.0f); - } + b3 = m_world->CreateBody(&bd); + b3->CreateFixture(&shape, 10.0f); + } - b2RevoluteJointDef jd; - b2Vec2 anchor; + b2RevoluteJointDef jd; + b2Vec2 anchor; - anchor.Set(-2.0f, 1.0f); - jd.Initialize(b1, b3, anchor); - jd.collideConnected = true; - m_world->CreateJoint(&jd); + anchor.Set(-2.0f, 1.0f); + jd.Initialize(b1, b3, anchor); + jd.collideConnected = true; + m_world->CreateJoint(&jd); - b2Body* b4; - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 0.25f); + b2Body* b4; + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 0.25f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 15.0f); - b4 = m_world->CreateBody(&bd); - b4->CreateFixture(&shape, 10.0f); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 15.0f); + b4 = m_world->CreateBody(&bd); + b4->CreateFixture(&shape, 10.0f); + } - anchor.Set(-7.0f, 15.0f); - jd.Initialize(b2, b4, anchor); - m_world->CreateJoint(&jd); + anchor.Set(-7.0f, 15.0f); + jd.Initialize(b2, b4, anchor); + m_world->CreateJoint(&jd); - b2Body* b5; - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 3.0f); - b5 = m_world->CreateBody(&bd); + b2Body* b5; + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 3.0f); + b5 = m_world->CreateBody(&bd); - b2PolygonShape shape; - b2FixtureDef fd; + b2PolygonShape shape; + b2FixtureDef fd; - fd.shape = &shape; - fd.density = 10.0f; - fd.friction = 0.1f; + fd.shape = &shape; + fd.density = 10.0f; + fd.friction = 0.1f; - shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); - b5->CreateFixture(&fd); + shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f); + b5->CreateFixture(&fd); - shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); + shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); - shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); - b5->CreateFixture(&fd); - } + shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f); + b5->CreateFixture(&fd); + } - anchor.Set(6.0f, 2.0f); - jd.Initialize(b1, b5, anchor); - m_world->CreateJoint(&jd); + anchor.Set(6.0f, 2.0f); + jd.Initialize(b1, b5, anchor); + m_world->CreateJoint(&jd); - b2Body* b6; - { - b2PolygonShape shape; - shape.SetAsBox(1.0f, 0.1f); + b2Body* b6; + { + b2PolygonShape shape; + shape.SetAsBox(1.0f, 0.1f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(6.5f, 4.1f); - b6 = m_world->CreateBody(&bd); - b6->CreateFixture(&shape, 30.0f); - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(6.5f, 4.1f); + b6 = m_world->CreateBody(&bd); + b6->CreateFixture(&shape, 30.0f); + } - anchor.Set(7.5f, 4.0f); - jd.Initialize(b5, b6, anchor); - m_world->CreateJoint(&jd); + anchor.Set(7.5f, 4.0f); + jd.Initialize(b5, b6, anchor); + m_world->CreateJoint(&jd); - b2Body* b7; - { - b2PolygonShape shape; - shape.SetAsBox(0.1f, 1.0f); + b2Body* b7; + { + b2PolygonShape shape; + shape.SetAsBox(0.1f, 1.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(7.4f, 1.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(7.4f, 1.0f); - b7 = m_world->CreateBody(&bd); - b7->CreateFixture(&shape, 10.0f); - } + b7 = m_world->CreateBody(&bd); + b7->CreateFixture(&shape, 10.0f); + } - b2DistanceJointDef djd; - djd.bodyA = b3; - djd.bodyB = b7; - djd.localAnchorA.Set(6.0f, 0.0f); - djd.localAnchorB.Set(0.0f, -1.0f); - b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); - djd.length = d.Length(); - m_world->CreateJoint(&djd); + b2DistanceJointDef djd; + djd.bodyA = b3; + djd.bodyB = b7; + djd.localAnchorA.Set(6.0f, 0.0f); + djd.localAnchorB.Set(0.0f, -1.0f); + b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->GetWorldPoint(djd.localAnchorA); + djd.length = d.Length(); + m_world->CreateJoint(&djd); - { - float32 radius = 0.2f; + { + float32 radius = 0.2f; - b2CircleShape shape; - shape.m_radius = radius; + b2CircleShape shape; + shape.m_radius = radius; - for (int32 i = 0; i < 4; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 10.0f); - } - } - } + for (int32 i = 0; i < 4; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 10.0f); + } + } + } - static Test* Create() - { - return new Dominos; - } + static Test* Create() + { + return new Dominos; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h index c87a9ca33a..0ea705d3ee 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h @@ -24,244 +24,152 @@ class DumpShell : public Test { public: - DumpShell() - { + DumpShell() + { + //Source code dump of Box2D scene: issue304-minimal-case.rube + // + // Created by R.U.B.E 1.3.0 + // Using Box2D version 2.3.0 + // Wed April 3 2013 04:33:28 + // + // This code is originally intended for use in the Box2D testbed, + // but you can easily use it in other applications by providing + // a b2World for use as the 'm_world' variable in the code below. -b2Vec2 g(0.000000000000000e+00f, 0.000000000000000e+00f); -m_world->SetGravity(g); -b2Body** bodies = (b2Body**)b2Alloc(3 * sizeof(b2Body*)); -b2Joint** joints = (b2Joint**)b2Alloc(2 * sizeof(b2Joint*)); -{ - b2BodyDef bd; - bd.type = b2BodyType(2); - bd.position.Set(1.304347801208496e+01f, 2.500000000000000e+00f); - bd.angle = 0.000000000000000e+00f; - bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - bd.angularVelocity = 0.000000000000000e+00f; - bd.linearDamping = 5.000000000000000e-01f; - bd.angularDamping = 5.000000000000000e-01f; - bd.allowSleep = bool(4); - bd.awake = bool(2); - bd.fixedRotation = bool(0); - bd.bullet = bool(0); - bd.active = bool(32); - bd.gravityScale = 1.000000000000000e+00f; - bodies[0] = m_world->CreateBody(&bd); + b2Vec2 g(0.000000000000000e+00f, -1.000000000000000e+01f); + m_world->SetGravity(g); + b2Body** bodies = (b2Body**)b2Alloc(3 * sizeof(b2Body*)); + b2Joint** joints = (b2Joint**)b2Alloc(0 * sizeof(b2Joint*)); + { + b2BodyDef bd; + bd.type = b2BodyType(0); + bd.position.Set(2.587699890136719e-02f, 5.515012264251709e+00f); + bd.angle = 0.000000000000000e+00f; + bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); + bd.angularVelocity = 0.000000000000000e+00f; + bd.linearDamping = 0.000000000000000e+00f; + bd.angularDamping = 0.000000000000000e+00f; + bd.allowSleep = bool(4); + bd.awake = bool(2); + bd.fixedRotation = bool(0); + bd.bullet = bool(0); + bd.active = bool(32); + bd.gravityScale = 1.000000000000000e+00f; + bodies[0] = m_world->CreateBody(&bd); - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+00f; - fd.restitution = 5.000000000000000e-01f; - fd.density = 1.000000000000000e+01f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2PolygonShape shape; - b2Vec2 vs[8]; - vs[0].Set(-6.900000095367432e+00f, -3.000000119209290e-01f); - vs[1].Set(2.000000029802322e-01f, -3.000000119209290e-01f); - vs[2].Set(2.000000029802322e-01f, 2.000000029802322e-01f); - vs[3].Set(-6.900000095367432e+00f, 2.000000029802322e-01f); - shape.Set(vs, 4); + { + b2FixtureDef fd; + fd.friction = 2.000000029802322e-01f; + fd.restitution = 0.000000000000000e+00f; + fd.density = 1.000000000000000e+00f; + fd.isSensor = bool(0); + fd.filter.categoryBits = uint16(1); + fd.filter.maskBits = uint16(65535); + fd.filter.groupIndex = int16(0); + b2PolygonShape shape; + b2Vec2 vs[8]; + vs[0].Set(7.733039855957031e-01f, -1.497260034084320e-01f); + vs[1].Set(-4.487270116806030e-01f, 1.138330027461052e-01f); + vs[2].Set(-1.880589962005615e+00f, -1.365900039672852e-01f); + vs[3].Set(3.972740173339844e-01f, -3.897832870483398e+00f); + shape.Set(vs, 4); - fd.shape = &shape; + fd.shape = &shape; - bodies[0]->CreateFixture(&fd); - } -} -{ - b2BodyDef bd; - bd.type = b2BodyType(2); - bd.position.Set(8.478260636329651e-01f, 2.500000000000000e+00f); - bd.angle = 0.000000000000000e+00f; - bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - bd.angularVelocity = 0.000000000000000e+00f; - bd.linearDamping = 5.000000000000000e-01f; - bd.angularDamping = 5.000000000000000e-01f; - bd.allowSleep = bool(4); - bd.awake = bool(2); - bd.fixedRotation = bool(0); - bd.bullet = bool(0); - bd.active = bool(32); - bd.gravityScale = 1.000000000000000e+00f; - bodies[1] = m_world->CreateBody(&bd); + bodies[0]->CreateFixture(&fd); + } + } + { + b2BodyDef bd; + bd.type = b2BodyType(2); + bd.position.Set(-3.122138977050781e-02f, 7.535382270812988e+00f); + bd.angle = -1.313644275069237e-02f; + bd.linearVelocity.Set(8.230687379837036e-01f, 7.775862514972687e-02f); + bd.angularVelocity = 3.705333173274994e-02f; + bd.linearDamping = 0.000000000000000e+00f; + bd.angularDamping = 0.000000000000000e+00f; + bd.allowSleep = bool(4); + bd.awake = bool(2); + bd.fixedRotation = bool(0); + bd.bullet = bool(0); + bd.active = bool(32); + bd.gravityScale = 1.000000000000000e+00f; + bodies[1] = m_world->CreateBody(&bd); - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+00f; - fd.restitution = 5.000000000000000e-01f; - fd.density = 1.000000000000000e+01f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2PolygonShape shape; - b2Vec2 vs[8]; - vs[0].Set(-3.228000104427338e-01f, -2.957000136375427e-01f); - vs[1].Set(6.885900020599365e+00f, -3.641000092029572e-01f); - vs[2].Set(6.907599925994873e+00f, 3.271999955177307e-01f); - vs[3].Set(-3.228000104427338e-01f, 2.825999855995178e-01f); - shape.Set(vs, 4); + { + b2FixtureDef fd; + fd.friction = 5.000000000000000e-01f; + fd.restitution = 0.000000000000000e+00f; + fd.density = 5.000000000000000e+00f; + fd.isSensor = bool(0); + fd.filter.categoryBits = uint16(1); + fd.filter.maskBits = uint16(65535); + fd.filter.groupIndex = int16(0); + b2PolygonShape shape; + b2Vec2 vs[8]; + vs[0].Set(3.473900079727173e+00f, -2.009889930486679e-01f); + vs[1].Set(3.457079887390137e+00f, 3.694039955735207e-02f); + vs[2].Set(-3.116359949111938e+00f, 2.348500071093440e-03f); + vs[3].Set(-3.109960079193115e+00f, -3.581250011920929e-01f); + vs[4].Set(-2.590820074081421e+00f, -5.472509860992432e-01f); + vs[5].Set(2.819370031356812e+00f, -5.402340292930603e-01f); + shape.Set(vs, 6); - fd.shape = &shape; + fd.shape = &shape; - bodies[1]->CreateFixture(&fd); - } -} + bodies[1]->CreateFixture(&fd); + } + } + { + b2BodyDef bd; + bd.type = b2BodyType(2); + bd.position.Set(-7.438077926635742e-01f, 6.626811981201172e+00f); + bd.angle = -1.884713363647461e+01f; + bd.linearVelocity.Set(1.785794943571091e-01f, 3.799796104431152e-07f); + bd.angularVelocity = -5.908820639888290e-06f; + bd.linearDamping = 0.000000000000000e+00f; + bd.angularDamping = 0.000000000000000e+00f; + bd.allowSleep = bool(4); + bd.awake = bool(2); + bd.fixedRotation = bool(0); + bd.bullet = bool(0); + bd.active = bool(32); + bd.gravityScale = 1.000000000000000e+00f; + bodies[2] = m_world->CreateBody(&bd); -{ - b2BodyDef bd; - bd.type = b2BodyType(0); - bd.position.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - bd.angle = 0.000000000000000e+00f; - bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - bd.angularVelocity = 0.000000000000000e+00f; - bd.linearDamping = 0.000000000000000e+00f; - bd.angularDamping = 0.000000000000000e+00f; - bd.allowSleep = bool(4); - bd.awake = bool(2); - bd.fixedRotation = bool(0); - bd.bullet = bool(0); - bd.active = bool(32); - bd.gravityScale = 1.000000000000000e+00f; - bodies[2] = m_world->CreateBody(&bd); + { + b2FixtureDef fd; + fd.friction = 9.499999880790710e-01f; + fd.restitution = 0.000000000000000e+00f; + fd.density = 1.000000000000000e+01f; + fd.isSensor = bool(0); + fd.filter.categoryBits = uint16(1); + fd.filter.maskBits = uint16(65535); + fd.filter.groupIndex = int16(-3); + b2PolygonShape shape; + b2Vec2 vs[8]; + vs[0].Set(1.639146506786346e-01f, 4.428443685173988e-02f); + vs[1].Set(-1.639146655797958e-01f, 4.428443685173988e-02f); + vs[2].Set(-1.639146655797958e-01f, -4.428443312644958e-02f); + vs[3].Set(1.639146357774734e-01f, -4.428444057703018e-02f); + shape.Set(vs, 4); - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+01f; - fd.restitution = 0.000000000000000e+00f; - fd.density = 0.000000000000000e+00f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2EdgeShape shape; - shape.m_radius = 9.999999776482582e-03f; - shape.m_vertex0.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex1.Set(4.452173995971680e+01f, 1.669565200805664e+01f); - shape.m_vertex2.Set(4.452173995971680e+01f, 0.000000000000000e+00f); - shape.m_vertex3.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_hasVertex0 = bool(0); - shape.m_hasVertex3 = bool(0); + fd.shape = &shape; - fd.shape = &shape; + bodies[2]->CreateFixture(&fd); + } + } + b2Free(joints); + b2Free(bodies); + joints = NULL; + bodies = NULL; - bodies[2]->CreateFixture(&fd); - } - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+01f; - fd.restitution = 0.000000000000000e+00f; - fd.density = 0.000000000000000e+00f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2EdgeShape shape; - shape.m_radius = 9.999999776482582e-03f; - shape.m_vertex0.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex1.Set(0.000000000000000e+00f, 1.669565200805664e+01f); - shape.m_vertex2.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex3.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_hasVertex0 = bool(0); - shape.m_hasVertex3 = bool(0); + } - fd.shape = &shape; - - bodies[2]->CreateFixture(&fd); - } - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+01f; - fd.restitution = 0.000000000000000e+00f; - fd.density = 0.000000000000000e+00f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2EdgeShape shape; - shape.m_radius = 9.999999776482582e-03f; - shape.m_vertex0.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex1.Set(0.000000000000000e+00f, 1.669565200805664e+01f); - shape.m_vertex2.Set(4.452173995971680e+01f, 1.669565200805664e+01f); - shape.m_vertex3.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_hasVertex0 = bool(0); - shape.m_hasVertex3 = bool(0); - - fd.shape = &shape; - - bodies[2]->CreateFixture(&fd); - } - { - b2FixtureDef fd; - fd.friction = 1.000000000000000e+01f; - fd.restitution = 0.000000000000000e+00f; - fd.density = 0.000000000000000e+00f; - fd.isSensor = bool(0); - fd.filter.categoryBits = uint16(1); - fd.filter.maskBits = uint16(65535); - fd.filter.groupIndex = int16(0); - b2EdgeShape shape; - shape.m_radius = 9.999999776482582e-03f; - shape.m_vertex0.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex1.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_vertex2.Set(4.452173995971680e+01f, 0.000000000000000e+00f); - shape.m_vertex3.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - shape.m_hasVertex0 = bool(0); - shape.m_hasVertex3 = bool(0); - - fd.shape = &shape; - - bodies[2]->CreateFixture(&fd); - } -} - -{ - b2PrismaticJointDef jd; - jd.bodyA = bodies[1]; - jd.bodyB = bodies[0]; - jd.collideConnected = bool(0); - jd.localAnchorA.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - jd.localAnchorB.Set(-1.219565200805664e+01f, 0.000000000000000e+00f); - jd.localAxisA.Set(-1.219565200805664e+01f, 0.000000000000000e+00f); - jd.referenceAngle = 0.000000000000000e+00f; - jd.enableLimit = bool(1); - jd.lowerTranslation = -2.000000000000000e+01f; - jd.upperTranslation = 0.000000000000000e+00f; - jd.enableMotor = bool(1); - jd.motorSpeed = 0.000000000000000e+00f; - jd.maxMotorForce = 1.000000000000000e+01f; - joints[0] = m_world->CreateJoint(&jd); -} -{ - b2RevoluteJointDef jd; - jd.bodyA = bodies[1]; - jd.bodyB = bodies[2]; - jd.collideConnected = bool(0); - jd.localAnchorA.Set(0.000000000000000e+00f, 0.000000000000000e+00f); - jd.localAnchorB.Set(8.478260636329651e-01f, 2.500000000000000e+00f); - jd.referenceAngle = 0.000000000000000e+00f; - jd.enableLimit = bool(0); - jd.lowerAngle = 0.000000000000000e+00f; - jd.upperAngle = 0.000000000000000e+00f; - jd.enableMotor = bool(0); - jd.motorSpeed = 0.000000000000000e+00f; - jd.maxMotorTorque = 0.000000000000000e+00f; - joints[1] = m_world->CreateJoint(&jd); -} -b2Free(joints); -b2Free(bodies); -joints = NULL; -bodies = NULL; - - - } - - static Test* Create() - { - return new DumpShell; - } + static Test* Create() + { + return new DumpShell; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h index 6dff9d2855..6ac113aab0 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h @@ -23,335 +23,335 @@ class DynamicTreeTest : public Test { public: - enum - { - e_actorCount = 128 - }; + enum + { + e_actorCount = 128 + }; - DynamicTreeTest() - { - m_worldExtent = 15.0f; - m_proxyExtent = 0.5f; + DynamicTreeTest() + { + m_worldExtent = 15.0f; + m_proxyExtent = 0.5f; - srand(888); + srand(888); - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - } + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + } - m_stepCount = 0; + m_stepCount = 0; - float32 h = m_worldExtent; - m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); - m_queryAABB.upperBound.Set(5.0f, 6.0f + h); + float32 h = m_worldExtent; + m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); + m_queryAABB.upperBound.Set(5.0f, 6.0f + h); - m_rayCastInput.p1.Set(-5.0, 5.0f + h); - m_rayCastInput.p2.Set(7.0f, -4.0f + h); - //m_rayCastInput.p1.Set(0.0f, 2.0f + h); - //m_rayCastInput.p2.Set(0.0f, -2.0f + h); - m_rayCastInput.maxFraction = 1.0f; + m_rayCastInput.p1.Set(-5.0, 5.0f + h); + m_rayCastInput.p2.Set(7.0f, -4.0f + h); + //m_rayCastInput.p1.Set(0.0f, 2.0f + h); + //m_rayCastInput.p2.Set(0.0f, -2.0f + h); + m_rayCastInput.maxFraction = 1.0f; - m_automated = false; - } + m_automated = false; + } - static Test* Create() - { - return new DynamicTreeTest; - } + static Test* Create() + { + return new DynamicTreeTest; + } - void Step(Settings* settings) - { - B2_NOT_USED(settings); + void Step(Settings* settings) + { + B2_NOT_USED(settings); - m_rayActor = NULL; - for (int32 i = 0; i < e_actorCount; ++i) - { - m_actors[i].fraction = 1.0f; - m_actors[i].overlap = false; - } + m_rayActor = NULL; + for (int32 i = 0; i < e_actorCount; ++i) + { + m_actors[i].fraction = 1.0f; + m_actors[i].overlap = false; + } - if (m_automated == true) - { - int32 actionCount = b2Max(1, e_actorCount >> 2); + if (m_automated == true) + { + int32 actionCount = b2Max(1, e_actorCount >> 2); - for (int32 i = 0; i < actionCount; ++i) - { - Action(); - } - } + for (int32 i = 0; i < actionCount; ++i) + { + Action(); + } + } - Query(); - RayCast(); + Query(); + RayCast(); - for (int32 i = 0; i < e_actorCount; ++i) - { - Actor* actor = m_actors + i; - if (actor->proxyId == b2_nullNode) - continue; + for (int32 i = 0; i < e_actorCount; ++i) + { + Actor* actor = m_actors + i; + if (actor->proxyId == b2_nullNode) + continue; - b2Color c(0.9f, 0.9f, 0.9f); - if (actor == m_rayActor && actor->overlap) - { - c.Set(0.9f, 0.6f, 0.6f); - } - else if (actor == m_rayActor) - { - c.Set(0.6f, 0.9f, 0.6f); - } - else if (actor->overlap) - { - c.Set(0.6f, 0.6f, 0.9f); - } + b2Color c(0.9f, 0.9f, 0.9f); + if (actor == m_rayActor && actor->overlap) + { + c.Set(0.9f, 0.6f, 0.6f); + } + else if (actor == m_rayActor) + { + c.Set(0.6f, 0.9f, 0.6f); + } + else if (actor->overlap) + { + c.Set(0.6f, 0.6f, 0.9f); + } - m_debugDraw.DrawAABB(&actor->aabb, c); - } + m_debugDraw.DrawAABB(&actor->aabb, c); + } - b2Color c(0.7f, 0.7f, 0.7f); - m_debugDraw.DrawAABB(&m_queryAABB, c); + b2Color c(0.7f, 0.7f, 0.7f); + m_debugDraw.DrawAABB(&m_queryAABB, c); - m_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); + m_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c); - b2Color c1(0.2f, 0.9f, 0.2f); - b2Color c2(0.9f, 0.2f, 0.2f); - m_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); - m_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); + b2Color c1(0.2f, 0.9f, 0.2f); + b2Color c2(0.9f, 0.2f, 0.2f); + m_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1); + m_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); - if (m_rayActor) - { - b2Color cr(0.2f, 0.2f, 0.9f); - b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); - m_debugDraw.DrawPoint(p, 6.0f, cr); - } + if (m_rayActor) + { + b2Color cr(0.2f, 0.2f, 0.9f); + b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCastInput.p2 - m_rayCastInput.p1); + m_debugDraw.DrawPoint(p, 6.0f, cr); + } - { - int32 height = m_tree.GetHeight(); - m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d", height); - m_textLine += 15; - } + { + int32 height = m_tree.GetHeight(); + m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d", height); + m_textLine += DRAW_STRING_NEW_LINE; + } - ++m_stepCount; - } + ++m_stepCount; + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - m_automated = !m_automated; - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_automated = !m_automated; + break; - case 'c': - CreateProxy(); - break; + case 'c': + CreateProxy(); + break; - case 'd': - DestroyProxy(); - break; + case 'd': + DestroyProxy(); + break; - case 'm': - MoveProxy(); - break; - } - } + case 'm': + MoveProxy(); + break; + } + } - bool QueryCallback(int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); - return true; - } + bool QueryCallback(int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); + return true; + } - float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - Actor* actor = (Actor*)m_tree.GetUserData(proxyId); + float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) + { + Actor* actor = (Actor*)m_tree.GetUserData(proxyId); - b2RayCastOutput output; - bool hit = actor->aabb.RayCast(&output, input); + b2RayCastOutput output; + bool hit = actor->aabb.RayCast(&output, input); - if (hit) - { - m_rayCastOutput = output; - m_rayActor = actor; - m_rayActor->fraction = output.fraction; - return output.fraction; - } + if (hit) + { + m_rayCastOutput = output; + m_rayActor = actor; + m_rayActor->fraction = output.fraction; + return output.fraction; + } - return input.maxFraction; - } + return input.maxFraction; + } private: - struct Actor - { - b2AABB aabb; - float32 fraction; - bool overlap; - int32 proxyId; - }; + struct Actor + { + b2AABB aabb; + float32 fraction; + bool overlap; + int32 proxyId; + }; - void GetRandomAABB(b2AABB* aabb) - { - b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); - //aabb->lowerBound.x = -m_proxyExtent; - //aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; - aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); - aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); - aabb->upperBound = aabb->lowerBound + w; - } + void GetRandomAABB(b2AABB* aabb) + { + b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); + //aabb->lowerBound.x = -m_proxyExtent; + //aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; + aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent); + aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent); + aabb->upperBound = aabb->lowerBound + w; + } - void MoveAABB(b2AABB* aabb) - { - b2Vec2 d; - d.x = RandomFloat(-0.5f, 0.5f); - d.y = RandomFloat(-0.5f, 0.5f); - //d.x = 2.0f; - //d.y = 0.0f; - aabb->lowerBound += d; - aabb->upperBound += d; + void MoveAABB(b2AABB* aabb) + { + b2Vec2 d; + d.x = RandomFloat(-0.5f, 0.5f); + d.y = RandomFloat(-0.5f, 0.5f); + //d.x = 2.0f; + //d.y = 0.0f; + aabb->lowerBound += d; + aabb->upperBound += d; - b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); - b2Vec2 min; min.Set(-m_worldExtent, 0.0f); - b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent); - b2Vec2 c = b2Clamp(c0, min, max); + b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); + b2Vec2 min; min.Set(-m_worldExtent, 0.0f); + b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent); + b2Vec2 c = b2Clamp(c0, min, max); - aabb->lowerBound += c - c0; - aabb->upperBound += c - c0; - } + aabb->lowerBound += c - c0; + aabb->upperBound += c - c0; + } - void CreateProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - GetRandomAABB(&actor->aabb); - actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); - return; - } - } - } + void CreateProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + GetRandomAABB(&actor->aabb); + actor->proxyId = m_tree.CreateProxy(actor->aabb, actor); + return; + } + } + } - void DestroyProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId != b2_nullNode) - { - m_tree.DestroyProxy(actor->proxyId); - actor->proxyId = b2_nullNode; - return; - } - } - } + void DestroyProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId != b2_nullNode) + { + m_tree.DestroyProxy(actor->proxyId); + actor->proxyId = b2_nullNode; + return; + } + } + } - void MoveProxy() - { - for (int32 i = 0; i < e_actorCount; ++i) - { - int32 j = rand() % e_actorCount; - Actor* actor = m_actors + j; - if (actor->proxyId == b2_nullNode) - { - continue; - } + void MoveProxy() + { + for (int32 i = 0; i < e_actorCount; ++i) + { + int32 j = rand() % e_actorCount; + Actor* actor = m_actors + j; + if (actor->proxyId == b2_nullNode) + { + continue; + } - b2AABB aabb0 = actor->aabb; - MoveAABB(&actor->aabb); - b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); - m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); - return; - } - } + b2AABB aabb0 = actor->aabb; + MoveAABB(&actor->aabb); + b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter(); + m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement); + return; + } + } - void Action() - { - int32 choice = rand() % 20; + void Action() + { + int32 choice = rand() % 20; - switch (choice) - { - case 0: - CreateProxy(); - break; + switch (choice) + { + case 0: + CreateProxy(); + break; - case 1: - DestroyProxy(); - break; + case 1: + DestroyProxy(); + break; - default: - MoveProxy(); - } - } + default: + MoveProxy(); + } + } - void Query() - { - m_tree.Query(this, m_queryAABB); + void Query() + { + m_tree.Query(this, m_queryAABB); - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } - bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); - B2_NOT_USED(overlap); - b2Assert(overlap == m_actors[i].overlap); - } - } + bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb); + B2_NOT_USED(overlap); + b2Assert(overlap == m_actors[i].overlap); + } + } - void RayCast() - { - m_rayActor = NULL; + void RayCast() + { + m_rayActor = NULL; - b2RayCastInput input = m_rayCastInput; + b2RayCastInput input = m_rayCastInput; - // Ray cast against the dynamic tree. - m_tree.RayCast(this, input); + // Ray cast against the dynamic tree. + m_tree.RayCast(this, input); - // Brute force ray cast. - Actor* bruteActor = NULL; - b2RayCastOutput bruteOutput; - for (int32 i = 0; i < e_actorCount; ++i) - { - if (m_actors[i].proxyId == b2_nullNode) - { - continue; - } + // Brute force ray cast. + Actor* bruteActor = NULL; + b2RayCastOutput bruteOutput; + for (int32 i = 0; i < e_actorCount; ++i) + { + if (m_actors[i].proxyId == b2_nullNode) + { + continue; + } - b2RayCastOutput output; - bool hit = m_actors[i].aabb.RayCast(&output, input); - if (hit) - { - bruteActor = m_actors + i; - bruteOutput = output; - input.maxFraction = output.fraction; - } - } + b2RayCastOutput output; + bool hit = m_actors[i].aabb.RayCast(&output, input); + if (hit) + { + bruteActor = m_actors + i; + bruteOutput = output; + input.maxFraction = output.fraction; + } + } - if (bruteActor != NULL) - { - b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); - } - } + if (bruteActor != NULL) + { + b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction); + } + } - float32 m_worldExtent; - float32 m_proxyExtent; + float32 m_worldExtent; + float32 m_proxyExtent; - b2DynamicTree m_tree; - b2AABB m_queryAABB; - b2RayCastInput m_rayCastInput; - b2RayCastOutput m_rayCastOutput; - Actor* m_rayActor; - Actor m_actors[e_actorCount]; - int32 m_stepCount; - bool m_automated; + b2DynamicTree m_tree; + b2AABB m_queryAABB; + b2RayCastInput m_rayCastInput; + b2RayCastOutput m_rayCastOutput; + Actor* m_rayActor; + Actor m_actors[e_actorCount]; + int32 m_stepCount; + bool m_automated; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h index 45defd74bd..09fd2061e7 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h @@ -22,228 +22,228 @@ class EdgeShapesCallback : public b2RayCastCallback { public: - EdgeShapesCallback() - { - m_fixture = NULL; - } + EdgeShapesCallback() + { + m_fixture = NULL; + } - float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) - { - m_fixture = fixture; - m_point = point; - m_normal = normal; + float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, + const b2Vec2& normal, float32 fraction) + { + m_fixture = fixture; + m_point = point; + m_normal = normal; - return fraction; - } + return fraction; + } - b2Fixture* m_fixture; - b2Vec2 m_point; - b2Vec2 m_normal; + b2Fixture* m_fixture; + b2Vec2 m_point; + b2Vec2 m_normal; }; class EdgeShapes : public Test { public: - enum - { - e_maxBodies = 256 - }; + enum + { + e_maxBodies = 256 + }; - EdgeShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + EdgeShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - float32 x1 = -20.0f; - float32 y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); - for (int32 i = 0; i < 80; ++i) - { - float32 x2 = x1 + 0.5f; - float32 y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); + float32 x1 = -20.0f; + float32 y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); + for (int32 i = 0; i < 80; ++i) + { + float32 x2 = x1 + 0.5f; + float32 y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); - b2EdgeShape shape; - shape.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; + shape.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); + ground->CreateFixture(&shape, 0.0f); - x1 = x2; - y1 = y2; - } - } + x1 = x2; + y1 = y2; + } + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - { - float32 w = 1.0f; - float32 b = w / (2.0f + b2Sqrt(2.0f)); - float32 s = b2Sqrt(2.0f) * b; + { + float32 w = 1.0f; + float32 b = w / (2.0f + b2Sqrt(2.0f)); + float32 s = b2Sqrt(2.0f) * b; - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - m_polygons[2].Set(vertices, 8); - } + m_polygons[2].Set(vertices, 8); + } - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - { - m_circle.m_radius = 0.5f; - } + { + m_circle.m_radius = 0.5f; + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); - m_angle = 0.0f; - } + m_angle = 0.0f; + } - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - b2BodyDef bd; + b2BodyDef bd; - float32 x = RandomFloat(-10.0f, 10.0f); - float32 y = RandomFloat(10.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); - bd.type = b2_dynamicBody; + float32 x = RandomFloat(-10.0f, 10.0f); + float32 y = RandomFloat(10.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); + bd.type = b2_dynamicBody; - if (index == 4) - { - bd.angularDamping = 0.02f; - } + if (index == 4) + { + bd.angularDamping = 0.02f; + } - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; - fd.density = 20.0f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; + fd.density = 20.0f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case '1': - case '2': - case '3': - case '4': - case '5': - Create(key - '1'); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case '1': + case '2': + case '3': + case '4': + case '5': + Create(key - '1'); + break; - case 'd': - DestroyBody(); - break; - } - } + case 'd': + DestroyBody(); + break; + } + } - void Step(Settings* settings) - { - bool advanceRay = settings->pause == 0 || settings->singleStep; + void Step(Settings* settings) + { + bool advanceRay = settings->pause == 0 || settings->singleStep; - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff"); - m_textLine += 15; + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff"); + m_textLine += DRAW_STRING_NEW_LINE; - float32 L = 25.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); - b2Vec2 point2 = point1 + d; + float32 L = 25.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); + b2Vec2 point2 = point1 + d; - EdgeShapesCallback callback; + EdgeShapesCallback callback; - m_world->RayCast(&callback, point1, point2); + m_world->RayCast(&callback, point1, point2); - if (callback.m_fixture) - { - m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + if (callback.m_fixture) + { + m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } - if (advanceRay) - { - m_angle += 0.25f * b2_pi / 180.0f; - } - } + if (advanceRay) + { + m_angle += 0.25f * b2_pi / 180.0f; + } + } - static Test* Create() - { - return new EdgeShapes; - } + static Test* Create() + { + return new EdgeShapes; + } - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; - float32 m_angle; + float32 m_angle; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h index c5306beaba..a89f262807 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h @@ -23,87 +23,87 @@ class EdgeTest : public Test { public: - EdgeTest() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + EdgeTest() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2Vec2 v1(-10.0f, 0.0f), v2(-7.0f, -2.0f), v3(-4.0f, 0.0f); - b2Vec2 v4(0.0f, 0.0f), v5(4.0f, 0.0f), v6(7.0f, 2.0f), v7(10.0f, 0.0f); + b2Vec2 v1(-10.0f, 0.0f), v2(-7.0f, -2.0f), v3(-4.0f, 0.0f); + b2Vec2 v4(0.0f, 0.0f), v5(4.0f, 0.0f), v6(7.0f, 2.0f), v7(10.0f, 0.0f); - b2EdgeShape shape; + b2EdgeShape shape; - shape.Set(v1, v2); - shape.m_hasVertex3 = true; - shape.m_vertex3 = v3; - ground->CreateFixture(&shape, 0.0f); + shape.Set(v1, v2); + shape.m_hasVertex3 = true; + shape.m_vertex3 = v3; + ground->CreateFixture(&shape, 0.0f); - shape.Set(v2, v3); - shape.m_hasVertex0 = true; - shape.m_hasVertex3 = true; - shape.m_vertex0 = v1; - shape.m_vertex3 = v4; - ground->CreateFixture(&shape, 0.0f); + shape.Set(v2, v3); + shape.m_hasVertex0 = true; + shape.m_hasVertex3 = true; + shape.m_vertex0 = v1; + shape.m_vertex3 = v4; + ground->CreateFixture(&shape, 0.0f); - shape.Set(v3, v4); - shape.m_hasVertex0 = true; - shape.m_hasVertex3 = true; - shape.m_vertex0 = v2; - shape.m_vertex3 = v5; - ground->CreateFixture(&shape, 0.0f); + shape.Set(v3, v4); + shape.m_hasVertex0 = true; + shape.m_hasVertex3 = true; + shape.m_vertex0 = v2; + shape.m_vertex3 = v5; + ground->CreateFixture(&shape, 0.0f); - shape.Set(v4, v5); - shape.m_hasVertex0 = true; - shape.m_hasVertex3 = true; - shape.m_vertex0 = v3; - shape.m_vertex3 = v6; - ground->CreateFixture(&shape, 0.0f); + shape.Set(v4, v5); + shape.m_hasVertex0 = true; + shape.m_hasVertex3 = true; + shape.m_vertex0 = v3; + shape.m_vertex3 = v6; + ground->CreateFixture(&shape, 0.0f); - shape.Set(v5, v6); - shape.m_hasVertex0 = true; - shape.m_hasVertex3 = true; - shape.m_vertex0 = v4; - shape.m_vertex3 = v7; - ground->CreateFixture(&shape, 0.0f); + shape.Set(v5, v6); + shape.m_hasVertex0 = true; + shape.m_hasVertex3 = true; + shape.m_vertex0 = v4; + shape.m_vertex3 = v7; + ground->CreateFixture(&shape, 0.0f); - shape.Set(v6, v7); - shape.m_hasVertex0 = true; - shape.m_vertex0 = v5; - ground->CreateFixture(&shape, 0.0f); - } + shape.Set(v6, v7); + shape.m_hasVertex0 = true; + shape.m_vertex0 = v5; + ground->CreateFixture(&shape, 0.0f); + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-0.5f, 0.6f); - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-0.5f, 0.6f); + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = 0.5f; - body->CreateFixture(&shape, 1.0f); - } + body->CreateFixture(&shape, 1.0f); + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(1.0f, 0.6f); - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(1.0f, 0.6f); + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - body->CreateFixture(&shape, 1.0f); - } - } + body->CreateFixture(&shape, 1.0f); + } + } - static Test* Create() - { - return new EdgeTest; - } + static Test* Create() + { + return new EdgeTest; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h index 285956e6ff..580707cefa 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h @@ -22,166 +22,165 @@ class Gears : public Test { public: - Gears() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Gears() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Gears co - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); - b2CircleShape circle2; - circle2.m_radius = 2.0f; - - b2BodyDef bd1; - bd1.type = b2_staticBody; - bd1.position.Set(10.0f, 9.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 0.0f); + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2BodyDef bd1; + bd1.type = b2_staticBody; + bd1.position.Set(10.0f, 9.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(10.0f, 8.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&box, 5.0f); + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(10.0f, 8.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&box, 5.0f); - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(10.0f, 6.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&circle2, 5.0f); + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(10.0f, 6.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&circle2, 5.0f); - b2RevoluteJointDef jd1; - jd1.Initialize(body2, body1, bd1.position); - b2Joint* joint1 = m_world->CreateJoint(&jd1); + b2RevoluteJointDef jd1; + jd1.Initialize(body2, body1, bd1.position); + b2Joint* joint1 = m_world->CreateJoint(&jd1); - b2RevoluteJointDef jd2; - jd2.Initialize(body2, body3, bd3.position); - b2Joint* joint2 = m_world->CreateJoint(&jd2); + b2RevoluteJointDef jd2; + jd2.Initialize(body2, body3, bd3.position); + b2Joint* joint2 = m_world->CreateJoint(&jd2); - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body3; - jd4.joint1 = joint1; - jd4.joint2 = joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_world->CreateJoint(&jd4); - } + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body3; + jd4.joint1 = joint1; + jd4.joint2 = joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_world->CreateJoint(&jd4); + } - { - b2CircleShape circle1; - circle1.m_radius = 1.0f; + { + b2CircleShape circle1; + circle1.m_radius = 1.0f; - b2CircleShape circle2; - circle2.m_radius = 2.0f; - - b2PolygonShape box; - box.SetAsBox(0.5f, 5.0f); + b2CircleShape circle2; + circle2.m_radius = 2.0f; + + b2PolygonShape box; + box.SetAsBox(0.5f, 5.0f); - b2BodyDef bd1; - bd1.type = b2_dynamicBody; - bd1.position.Set(-3.0f, 12.0f); - b2Body* body1 = m_world->CreateBody(&bd1); - body1->CreateFixture(&circle1, 5.0f); + b2BodyDef bd1; + bd1.type = b2_dynamicBody; + bd1.position.Set(-3.0f, 12.0f); + b2Body* body1 = m_world->CreateBody(&bd1); + body1->CreateFixture(&circle1, 5.0f); - b2RevoluteJointDef jd1; - jd1.bodyA = ground; - jd1.bodyB = body1; - jd1.localAnchorA = ground->GetLocalPoint(bd1.position); - jd1.localAnchorB = body1->GetLocalPoint(bd1.position); - jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); + b2RevoluteJointDef jd1; + jd1.bodyA = ground; + jd1.bodyB = body1; + jd1.localAnchorA = ground->GetLocalPoint(bd1.position); + jd1.localAnchorB = body1->GetLocalPoint(bd1.position); + jd1.referenceAngle = body1->GetAngle() - ground->GetAngle(); + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1); - b2BodyDef bd2; - bd2.type = b2_dynamicBody; - bd2.position.Set(0.0f, 12.0f); - b2Body* body2 = m_world->CreateBody(&bd2); - body2->CreateFixture(&circle2, 5.0f); + b2BodyDef bd2; + bd2.type = b2_dynamicBody; + bd2.position.Set(0.0f, 12.0f); + b2Body* body2 = m_world->CreateBody(&bd2); + body2->CreateFixture(&circle2, 5.0f); - b2RevoluteJointDef jd2; - jd2.Initialize(ground, body2, bd2.position); - m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); + b2RevoluteJointDef jd2; + jd2.Initialize(ground, body2, bd2.position); + m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2); - b2BodyDef bd3; - bd3.type = b2_dynamicBody; - bd3.position.Set(2.5f, 12.0f); - b2Body* body3 = m_world->CreateBody(&bd3); - body3->CreateFixture(&box, 5.0f); + b2BodyDef bd3; + bd3.type = b2_dynamicBody; + bd3.position.Set(2.5f, 12.0f); + b2Body* body3 = m_world->CreateBody(&bd3); + body3->CreateFixture(&box, 5.0f); - b2PrismaticJointDef jd3; - jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); - jd3.lowerTranslation = -5.0f; - jd3.upperTranslation = 5.0f; - jd3.enableLimit = true; + b2PrismaticJointDef jd3; + jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f)); + jd3.lowerTranslation = -5.0f; + jd3.upperTranslation = 5.0f; + jd3.enableLimit = true; - m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); + m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3); - b2GearJointDef jd4; - jd4.bodyA = body1; - jd4.bodyB = body2; - jd4.joint1 = m_joint1; - jd4.joint2 = m_joint2; - jd4.ratio = circle2.m_radius / circle1.m_radius; - m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); + b2GearJointDef jd4; + jd4.bodyA = body1; + jd4.bodyB = body2; + jd4.joint1 = m_joint1; + jd4.joint2 = m_joint2; + jd4.ratio = circle2.m_radius / circle1.m_radius; + m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); - b2GearJointDef jd5; - jd5.bodyA = body2; - jd5.bodyB = body3; - jd5.joint1 = m_joint2; - jd5.joint2 = m_joint3; - jd5.ratio = -1.0f / circle2.m_radius; - m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); - } - } + b2GearJointDef jd5; + jd5.bodyA = body2; + jd5.bodyB = body3; + jd5.joint1 = m_joint2; + jd5.joint2 = m_joint3; + jd5.ratio = -1.0f / circle2.m_radius; + m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 0: - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case 0: + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - float32 ratio, value; - - ratio = m_joint4->GetRatio(); - value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); - m_debugDraw.DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float) ratio, (float) value); - m_textLine += 15; + float32 ratio, value; + + ratio = m_joint4->GetRatio(); + value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle(); + m_debugDraw.DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4.2f", (float) ratio, (float) value); + m_textLine += DRAW_STRING_NEW_LINE; - ratio = m_joint5->GetRatio(); - value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); - m_debugDraw.DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float) ratio, (float) value); - m_textLine += 15; - } + ratio = m_joint5->GetRatio(); + value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTranslation(); + m_debugDraw.DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.2f", (float) ratio, (float) value); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Gears; - } + static Test* Create() + { + return new Gears; + } - b2RevoluteJoint* m_joint1; - b2RevoluteJoint* m_joint2; - b2PrismaticJoint* m_joint3; - b2GearJoint* m_joint4; - b2GearJoint* m_joint5; + b2RevoluteJoint* m_joint1; + b2RevoluteJoint* m_joint2; + b2PrismaticJoint* m_joint3; + b2GearJoint* m_joint4; + b2GearJoint* m_joint5; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h new file mode 100644 index 0000000000..9244a66d6b --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef MOBILE_H +#define MOBILE_H + +class Mobile : public Test +{ +public: + + enum + { + e_depth = 4 + }; + + Mobile() + { + b2Body* ground; + + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } + + float32 a = 0.5f; + b2Vec2 h(0.0f, a); + + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } + + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float32 offset, float32 a) + { + float32 density = 20.0f; + b2Vec2 h(0.0f, a); + + b2Vec2 p = parent->GetPosition() + localAnchor - h; + + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); + + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); + + if (depth == e_depth) + { + return body; + } + + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; + + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); + + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); + + return body; + } + + static Test* Create() + { + return new Mobile; + } +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h new file mode 100644 index 0000000000..50e852e331 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h @@ -0,0 +1,105 @@ +/* +* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef MOBILE_BALANCED_H +#define MOBILE_BALANCED_H + +class MobileBalanced : public Test +{ +public: + + enum + { + e_depth = 4 + }; + + MobileBalanced() + { + b2Body* ground; + + // Create ground body. + { + b2BodyDef bodyDef; + bodyDef.position.Set(0.0f, 20.0f); + ground = m_world->CreateBody(&bodyDef); + } + + float32 a = 0.5f; + b2Vec2 h(0.0f, a); + + b2Body* root = AddNode(ground, b2Vec2_zero, 0, 3.0f, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = ground; + jointDef.bodyB = root; + jointDef.localAnchorA.SetZero(); + jointDef.localAnchorB = h; + m_world->CreateJoint(&jointDef); + } + + b2Body* AddNode(b2Body* parent, const b2Vec2& localAnchor, int32 depth, float32 offset, float32 a) + { + float32 density = 20.0f; + b2Vec2 h(0.0f, a); + + b2Vec2 p = parent->GetPosition() + localAnchor - h; + + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + bodyDef.position = p; + b2Body* body = m_world->CreateBody(&bodyDef); + + b2PolygonShape shape; + shape.SetAsBox(0.25f * a, a); + body->CreateFixture(&shape, density); + + if (depth == e_depth) + { + return body; + } + + shape.SetAsBox(offset, 0.25f * a, b2Vec2(0, -a), 0.0f); + body->CreateFixture(&shape, density); + + b2Vec2 a1 = b2Vec2(offset, -a); + b2Vec2 a2 = b2Vec2(-offset, -a); + b2Body* body1 = AddNode(body, a1, depth + 1, 0.5f * offset, a); + b2Body* body2 = AddNode(body, a2, depth + 1, 0.5f * offset, a); + + b2RevoluteJointDef jointDef; + jointDef.bodyA = body; + jointDef.localAnchorB = h; + + jointDef.localAnchorA = a1; + jointDef.bodyB = body1; + m_world->CreateJoint(&jointDef); + + jointDef.localAnchorA = a2; + jointDef.bodyB = body2; + m_world->CreateJoint(&jointDef); + + return body; + } + + static Test* Create() + { + return new MobileBalanced; + } +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h new file mode 100644 index 0000000000..cd3ded9bae --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked as such, and must not be +* misrepresented as being the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef MOTOR_JOINT_H +#define MOTOR_JOINT_H + +/// This test shows how to use a motor joint. A motor joint +/// can be used to animate a dynamic body. With finite motor forces +/// the body can be blocked by collision with other bodies. +class MotorJoint : public Test +{ +public: + MotorJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + + b2EdgeShape shape; + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + + b2FixtureDef fd; + fd.shape = &shape; + + ground->CreateFixture(&fd); + } + + // Define motorized body + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 8.0f); + b2Body* body = m_world->CreateBody(&bd); + + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.5f); + + b2FixtureDef fd; + fd.shape = &shape; + fd.friction = 0.6f; + fd.density = 2.0f; + body->CreateFixture(&fd); + + b2MotorJointDef mjd; + mjd.Initialize(ground, body); + mjd.maxForce = 1000.0f; + mjd.maxTorque = 1000.0f; + m_joint = (b2MotorJoint*)m_world->CreateJoint(&mjd); + } + + m_go = false; + m_time = 0.0f; + } + + void Keyboard(unsigned char key) + { + switch (key) + { + case 's': + m_go = !m_go; + break; + } + } + + void Step(Settings* settings) + { + if (m_go && settings->hz > 0.0f) + { + m_time += 1.0f / settings->hz; + } + + b2Vec2 linearOffset; + linearOffset.x = 6.0f * sinf(2.0f * m_time); + linearOffset.y = 8.0f + 4.0f * sinf(1.0f * m_time); + + float32 angularOffset = 4.0f * m_time; + + m_joint->SetLinearOffset(linearOffset); + m_joint->SetAngularOffset(angularOffset); + + m_debugDraw.DrawPoint(linearOffset, 4.0f, b2Color(0.9f, 0.9f, 0.9f)); + + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Keys: (s) pause"); + m_textLine += 15; + } + + static Test* Create() + { + return new MotorJoint; + } + + b2MotorJoint* m_joint; + float32 m_time; + bool m_go; +}; + +#endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h index cd5173b089..69e339a855 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h @@ -23,98 +23,110 @@ class OneSidedPlatform : public Test { public: - enum State - { - e_unknown, - e_above, - e_below - }; + enum State + { + e_unknown, + e_above, + e_below + }; - OneSidedPlatform() - { - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + OneSidedPlatform() + { + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Platform - { - b2BodyDef bd; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + // Platform + { + b2BodyDef bd; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(3.0f, 0.5f); - m_platform = body->CreateFixture(&shape, 0.0f); + b2PolygonShape shape; + shape.SetAsBox(3.0f, 0.5f); + m_platform = body->CreateFixture(&shape, 0.0f); - m_bottom = 10.0f - 0.5f; - m_top = 10.0f + 0.5f; - } + m_bottom = 10.0f - 0.5f; + m_top = 10.0f + 0.5f; + } - // Actor - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 12.0f); - b2Body* body = m_world->CreateBody(&bd); + // Actor + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 12.0f); + b2Body* body = m_world->CreateBody(&bd); - m_radius = 0.5f; - b2CircleShape shape; - shape.m_radius = m_radius; - m_character = body->CreateFixture(&shape, 20.0f); + m_radius = 0.5f; + b2CircleShape shape; + shape.m_radius = m_radius; + m_character = body->CreateFixture(&shape, 20.0f); - body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + body->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - m_state = e_unknown; - } - } + m_state = e_unknown; + } + } - void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) - { - Test::PreSolve(contact, oldManifold); + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + Test::PreSolve(contact, oldManifold); - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA != m_platform && fixtureA != m_character) - { - return; - } + if (fixtureA != m_platform && fixtureA != m_character) + { + return; + } - if (fixtureB != m_platform && fixtureB != m_character) - { - return; - } + if (fixtureB != m_platform && fixtureB != m_character) + { + return; + } - b2Vec2 position = m_character->GetBody()->GetPosition(); +#if 1 + b2Vec2 position = m_character->GetBody()->GetPosition(); - if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) - { + if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) + { + contact->SetEnabled(false); + } +#else + b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); + if (v.y > 0.0f) + { contact->SetEnabled(false); } - } +#endif + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); + m_textLine += DRAW_STRING_NEW_LINE; - static Test* Create() - { - return new OneSidedPlatform; - } + b2Vec2 v = m_character->GetBody()->GetLinearVelocity(); + m_debugDraw.DrawString(5, m_textLine, "Character Linear Velocity: %f", v.y); + m_textLine += DRAW_STRING_NEW_LINE; + } - float32 m_radius, m_top, m_bottom; - State m_state; - b2Fixture* m_platform; - b2Fixture* m_character; + static Test* Create() + { + return new OneSidedPlatform; + } + + float32 m_radius, m_top, m_bottom; + State m_state; + b2Fixture* m_platform; + b2Fixture* m_character; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h index 4557d50696..9d5982f25f 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h @@ -24,146 +24,146 @@ class Pinball : public Test { public: - Pinball() - { - // Ground body - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Pinball() + { + // Ground body + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2Vec2 vs[5]; - vs[0].Set(0.0f, -2.0f); - vs[1].Set(8.0f, 6.0f); - vs[2].Set(8.0f, 20.0f); - vs[3].Set(-8.0f, 20.0f); - vs[4].Set(-8.0f, 6.0f); + b2Vec2 vs[5]; + vs[0].Set(0.0f, -2.0f); + vs[1].Set(8.0f, 6.0f); + vs[2].Set(8.0f, 20.0f); + vs[3].Set(-8.0f, 20.0f); + vs[4].Set(-8.0f, 6.0f); - b2ChainShape loop; - loop.CreateLoop(vs, 5); - b2FixtureDef fd; - fd.shape = &loop; - fd.density = 0.0f; - ground->CreateFixture(&fd); - } + b2ChainShape loop; + loop.CreateLoop(vs, 5); + b2FixtureDef fd; + fd.shape = &loop; + fd.density = 0.0f; + ground->CreateFixture(&fd); + } - // Flippers - { - b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); + // Flippers + { + b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position = p1; - b2Body* leftFlipper = m_world->CreateBody(&bd); + bd.position = p1; + b2Body* leftFlipper = m_world->CreateBody(&bd); - bd.position = p2; - b2Body* rightFlipper = m_world->CreateBody(&bd); + bd.position = p2; + b2Body* rightFlipper = m_world->CreateBody(&bd); - b2PolygonShape box; - box.SetAsBox(1.75f, 0.1f); + b2PolygonShape box; + box.SetAsBox(1.75f, 0.1f); - b2FixtureDef fd; - fd.shape = &box; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &box; + fd.density = 1.0f; - leftFlipper->CreateFixture(&fd); - rightFlipper->CreateFixture(&fd); + leftFlipper->CreateFixture(&fd); + rightFlipper->CreateFixture(&fd); - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.localAnchorB.SetZero(); - jd.enableMotor = true; - jd.maxMotorTorque = 1000.0f; - jd.enableLimit = true; + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.localAnchorB.SetZero(); + jd.enableMotor = true; + jd.maxMotorTorque = 1000.0f; + jd.enableLimit = true; - jd.motorSpeed = 0.0f; - jd.localAnchorA = p1; - jd.bodyB = leftFlipper; - jd.lowerAngle = -30.0f * b2_pi / 180.0f; - jd.upperAngle = 5.0f * b2_pi / 180.0f; - m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + jd.motorSpeed = 0.0f; + jd.localAnchorA = p1; + jd.bodyB = leftFlipper; + jd.lowerAngle = -30.0f * b2_pi / 180.0f; + jd.upperAngle = 5.0f * b2_pi / 180.0f; + m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - jd.motorSpeed = 0.0f; - jd.localAnchorA = p2; - jd.bodyB = rightFlipper; - jd.lowerAngle = -5.0f * b2_pi / 180.0f; - jd.upperAngle = 30.0f * b2_pi / 180.0f; - m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + jd.motorSpeed = 0.0f; + jd.localAnchorA = p2; + jd.bodyB = rightFlipper; + jd.lowerAngle = -5.0f * b2_pi / 180.0f; + jd.upperAngle = 30.0f * b2_pi / 180.0f; + m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - // Circle character - { - b2BodyDef bd; - bd.position.Set(1.0f, 15.0f); - bd.type = b2_dynamicBody; - bd.bullet = true; + // Circle character + { + b2BodyDef bd; + bd.position.Set(1.0f, 15.0f); + bd.type = b2_dynamicBody; + bd.bullet = true; - m_ball = m_world->CreateBody(&bd); + m_ball = m_world->CreateBody(&bd); - b2CircleShape shape; - shape.m_radius = 0.2f; + b2CircleShape shape; + shape.m_radius = 0.2f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - m_ball->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + m_ball->CreateFixture(&fd); + } - m_button = false; - } + m_button = false; + } - void Step(Settings* settings) - { - if (m_button) - { - m_leftJoint->SetMotorSpeed(20.0f); - m_rightJoint->SetMotorSpeed(-20.0f); - } - else - { - m_leftJoint->SetMotorSpeed(-10.0f); - m_rightJoint->SetMotorSpeed(10.0f); - } + void Step(Settings* settings) + { + if (m_button) + { + m_leftJoint->SetMotorSpeed(20.0f); + m_rightJoint->SetMotorSpeed(-20.0f); + } + else + { + m_leftJoint->SetMotorSpeed(-10.0f); + m_rightJoint->SetMotorSpeed(10.0f); + } - Test::Step(settings); + Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press 'a' to control the flippers"); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "Press 'a' to control the flippers"); + m_textLine += DRAW_STRING_NEW_LINE; - } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - case 'A': - m_button = true; - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + case 'A': + m_button = true; + break; + } + } - void KeyboardUp(unsigned char key) - { - switch (key) - { - case 'a': - case 'A': - m_button = false; - break; - } - } + void KeyboardUp(unsigned char key) + { + switch (key) + { + case 'a': + case 'A': + m_button = false; + break; + } + } - static Test* Create() - { - return new Pinball; - } + static Test* Create() + { + return new Pinball; + } - b2RevoluteJoint* m_leftJoint; - b2RevoluteJoint* m_rightJoint; - b2Body* m_ball; - bool m_button; + b2RevoluteJoint* m_leftJoint; + b2RevoluteJoint* m_rightJoint; + b2Body* m_ball; + bool m_button; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h index 941ee42ec5..0316a7b16e 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h @@ -22,101 +22,101 @@ class PolyCollision : public Test { public: - PolyCollision() - { - { - m_polygonA.SetAsBox(0.2f, 0.4f); - m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); - } + PolyCollision() + { + { + m_polygonA.SetAsBox(0.2f, 0.4f); + m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); + } - { - m_polygonB.SetAsBox(0.5f, 0.5f); - m_positionB.Set(19.345284f, 1.5632932f); - m_angleB = 1.9160721f; - m_transformB.Set(m_positionB, m_angleB); - } - } + { + m_polygonB.SetAsBox(0.5f, 0.5f); + m_positionB.Set(19.345284f, 1.5632932f); + m_angleB = 1.9160721f; + m_transformB.Set(m_positionB, m_angleB); + } + } - static Test* Create() - { - return new PolyCollision; - } + static Test* Create() + { + return new PolyCollision; + } - void Step(Settings* settings) - { - B2_NOT_USED(settings); + void Step(Settings* settings) + { + B2_NOT_USED(settings); - b2Manifold manifold; - b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); + b2Manifold manifold; + b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB, m_transformB); - b2WorldManifold worldManifold; - worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); + b2WorldManifold worldManifold; + worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radius, m_transformB, m_polygonB.m_radius); - m_debugDraw.DrawString(5, m_textLine, "point count = %d", manifold.pointCount); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "point count = %d", manifold.pointCount); + m_textLine += DRAW_STRING_NEW_LINE; - { - b2Color color(0.9f, 0.9f, 0.9f); - b2Vec2 v[b2_maxPolygonVertices]; - for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i) - { - v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); - } - m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount, color); + { + b2Color color(0.9f, 0.9f, 0.9f); + b2Vec2 v[b2_maxPolygonVertices]; + for (int32 i = 0; i < m_polygonA.m_count; ++i) + { + v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]); + } + m_debugDraw.DrawPolygon(v, m_polygonA.m_count, color); - for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i) - { - v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, color); - } + for (int32 i = 0; i < m_polygonB.m_count; ++i) + { + v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(v, m_polygonB.m_count, color); + } - for (int32 i = 0; i < manifold.pointCount; ++i) - { - m_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); - } - } + for (int32 i = 0; i < manifold.pointCount; ++i) + { + m_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.9f, 0.3f, 0.3f)); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - m_positionB.x -= 0.1f; - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_positionB.x -= 0.1f; + break; - case 'd': - m_positionB.x += 0.1f; - break; + case 'd': + m_positionB.x += 0.1f; + break; - case 's': - m_positionB.y -= 0.1f; - break; + case 's': + m_positionB.y -= 0.1f; + break; - case 'w': - m_positionB.y += 0.1f; - break; + case 'w': + m_positionB.y += 0.1f; + break; - case 'q': - m_angleB += 0.1f * b2_pi; - break; + case 'q': + m_angleB += 0.1f * b2_pi; + break; - case 'e': - m_angleB -= 0.1f * b2_pi; - break; - } + case 'e': + m_angleB -= 0.1f * b2_pi; + break; + } - m_transformB.Set(m_positionB, m_angleB); - } + m_transformB.Set(m_positionB, m_angleB); + } - b2PolygonShape m_polygonA; - b2PolygonShape m_polygonB; + b2PolygonShape m_polygonA; + b2PolygonShape m_polygonB; - b2Transform m_transformA; - b2Transform m_transformB; + b2Transform m_transformA; + b2Transform m_transformB; - b2Vec2 m_positionB; - float32 m_angleB; + b2Vec2 m_positionB; + float32 m_angleB; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h index 6713e0086c..532071a58d 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h @@ -22,274 +22,278 @@ /// This tests stacking. It also shows how to use b2World::Query /// and b2TestOverlap. -const int32 k_maxBodies = 256; - /// This callback is called by b2World::QueryAABB. We find all the fixtures /// that overlap an AABB. Of those, we use b2TestOverlap to determine which fixtures /// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border. class PolyShapesCallback : public b2QueryCallback { public: - - enum - { - e_maxCount = 4 - }; + + enum + { + e_maxCount = 4 + }; - PolyShapesCallback() - { - m_count = 0; - } + PolyShapesCallback() + { + m_count = 0; + } - void DrawFixture(b2Fixture* fixture) - { - b2Color color(0.95f, 0.95f, 0.6f); - const b2Transform& xf = fixture->GetBody()->GetTransform(); + void DrawFixture(b2Fixture* fixture) + { + b2Color color(0.95f, 0.95f, 0.6f); + const b2Transform& xf = fixture->GetBody()->GetTransform(); - switch (fixture->GetType()) - { - case b2Shape::e_circle: - { - b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); + switch (fixture->GetType()) + { + case b2Shape::e_circle: + { + b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); - b2Vec2 center = b2Mul(xf, circle->m_p); - float32 radius = circle->m_radius; + b2Vec2 center = b2Mul(xf, circle->m_p); + float32 radius = circle->m_radius; - m_debugDraw->DrawCircle(center, radius, color); - } - break; + m_debugDraw->DrawCircle(center, radius, color); + } + break; - case b2Shape::e_polygon: - { - b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); - int32 vertexCount = poly->m_vertexCount; - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; + case b2Shape::e_polygon: + { + b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); + int32 vertexCount = poly->m_count; + b2Assert(vertexCount <= b2_maxPolygonVertices); + b2Vec2 vertices[b2_maxPolygonVertices]; - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, poly->m_vertices[i]); - } + for (int32 i = 0; i < vertexCount; ++i) + { + vertices[i] = b2Mul(xf, poly->m_vertices[i]); + } - m_debugDraw->DrawPolygon(vertices, vertexCount, color); - } - break; - - default: - break; - } - } + m_debugDraw->DrawPolygon(vertices, vertexCount, color); + } + break; + + default: + break; + } + } - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - bool ReportFixture(b2Fixture* fixture) - { - if (m_count == e_maxCount) - { - return false; - } + /// Called for each fixture found in the query AABB. + /// @return false to terminate the query. + bool ReportFixture(b2Fixture* fixture) + { + if (m_count == e_maxCount) + { + return false; + } - b2Body* body = fixture->GetBody(); - b2Shape* shape = fixture->GetShape(); + b2Body* body = fixture->GetBody(); + b2Shape* shape = fixture->GetShape(); - bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); + bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTransform(), m_transform); - if (overlap) - { - DrawFixture(fixture); - ++m_count; - } + if (overlap) + { + DrawFixture(fixture); + ++m_count; + } - return true; - } + return true; + } - b2CircleShape m_circle; - b2Transform m_transform; - b2Draw* m_debugDraw; - int32 m_count; + b2CircleShape m_circle; + b2Transform m_transform; + b2Draw* m_debugDraw; + int32 m_count; }; class PolyShapes : public Test { public: - PolyShapes() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + enum + { + e_maxBodies = 256 + }; - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } - - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + PolyShapes() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - float32 w = 1.0f; - float32 b = w / (2.0f + b2Sqrt(2.0f)); - float32 s = b2Sqrt(2.0f) * b; + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } + + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - m_polygons[2].Set(vertices, 8); - } + { + float32 w = 1.0f; + float32 b = w / (2.0f + b2Sqrt(2.0f)); + float32 s = b2Sqrt(2.0f) * b; - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - { - m_circle.m_radius = 0.5f; - } + m_polygons[2].Set(vertices, 8); + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + { + m_circle.m_radius = 0.5f; + } - b2BodyDef bd; - bd.type = b2_dynamicBody; + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); + } - float32 x = RandomFloat(-2.0f, 2.0f); - bd.position.Set(x, 10.0f); - bd.angle = RandomFloat(-b2_pi, b2_pi); + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - if (index == 4) - { - bd.angularDamping = 0.02f; - } + b2BodyDef bd; + bd.type = b2_dynamicBody; - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + float32 x = RandomFloat(-2.0f, 2.0f); + bd.position.Set(x, 10.0f); + bd.angle = RandomFloat(-b2_pi, b2_pi); - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.density = 1.0f; - fd.friction = 0.3f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.density = 1.0f; - fd.friction = 0.3f; + if (index == 4) + { + bd.angularDamping = 0.02f; + } - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - m_bodyIndex = (m_bodyIndex + 1) % k_maxBodies; - } + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.density = 1.0f; + fd.friction = 0.3f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.density = 1.0f; + fd.friction = 0.3f; - void DestroyBody() - { - for (int32 i = 0; i < k_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case '1': - case '2': - case '3': - case '4': - case '5': - Create(key - '1'); - break; + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - case 'a': - for (int32 i = 0; i < k_maxBodies; i += 2) - { - if (m_bodies[i]) - { - bool active = m_bodies[i]->IsActive(); - m_bodies[i]->SetActive(!active); - } - } - break; + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - case 'd': - DestroyBody(); - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case '1': + case '2': + case '3': + case '4': + case '5': + Create(key - '1'); + break; - void Step(Settings* settings) - { - Test::Step(settings); + case 'a': + for (int32 i = 0; i < e_maxBodies; i += 2) + { + if (m_bodies[i]) + { + bool active = m_bodies[i]->IsActive(); + m_bodies[i]->SetActive(!active); + } + } + break; - PolyShapesCallback callback; - callback.m_circle.m_radius = 2.0f; - callback.m_circle.m_p.Set(0.0f, 1.1f); - callback.m_transform.SetIdentity(); - callback.m_debugDraw = &m_debugDraw; + case 'd': + DestroyBody(); + break; + } + } - b2AABB aabb; - callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); + void Step(Settings* settings) + { + Test::Step(settings); - m_world->QueryAABB(&callback, aabb); + PolyShapesCallback callback; + callback.m_circle.m_radius = 2.0f; + callback.m_circle.m_p.Set(0.0f, 1.1f); + callback.m_transform.SetIdentity(); + callback.m_debugDraw = &m_debugDraw; - b2Color color(0.4f, 0.7f, 0.8f); - m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); + b2AABB aabb; + callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0); - m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff"); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)activate some bodies"); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy a body"); - m_textLine += 15; - } + m_world->QueryAABB(&callback, aabb); - static Test* Create() - { - return new PolyShapes; - } + b2Color color(0.4f, 0.7f, 0.8f); + m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_radius, color); - int32 m_bodyIndex; - b2Body* m_bodies[k_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff"); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)activate some bodies"); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy a body"); + m_textLine += DRAW_STRING_NEW_LINE; + } + + static Test* Create() + { + return new PolyShapes; + } + + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h index 4ad9552a18..731745c64d 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h @@ -23,85 +23,85 @@ class Prismatic : public Test { public: - Prismatic() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Prismatic() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(2.0f, 0.5f); + { + b2PolygonShape shape; + shape.SetAsBox(2.0f, 0.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f, 10.0f); - bd.angle = 0.5f * b2_pi; - bd.allowSleep = false; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f, 10.0f); + bd.angle = 0.5f * b2_pi; + bd.allowSleep = false; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - b2PrismaticJointDef pjd; + b2PrismaticJointDef pjd; - // Bouncy limit - b2Vec2 axis(2.0f, 1.0f); - axis.Normalize(); - pjd.Initialize(ground, body, b2Vec2(0.0f, 0.0f), axis); + // Bouncy limit + b2Vec2 axis(2.0f, 1.0f); + axis.Normalize(); + pjd.Initialize(ground, body, b2Vec2(0.0f, 0.0f), axis); - // Non-bouncy limit - //pjd.Initialize(ground, body, b2Vec2(-10.0f, 10.0f), b2Vec2(1.0f, 0.0f)); + // Non-bouncy limit + //pjd.Initialize(ground, body, b2Vec2(-10.0f, 10.0f), b2Vec2(1.0f, 0.0f)); - pjd.motorSpeed = 10.0f; - pjd.maxMotorForce = 10000.0f; - pjd.enableMotor = true; - pjd.lowerTranslation = 0.0f; - pjd.upperTranslation = 20.0f; - pjd.enableLimit = true; + pjd.motorSpeed = 10.0f; + pjd.maxMotorForce = 10000.0f; + pjd.enableMotor = true; + pjd.lowerTranslation = 0.0f; + pjd.upperTranslation = 20.0f; + pjd.enableLimit = true; - m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } - } + m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'l': - m_joint->EnableLimit(!m_joint->IsLimitEnabled()); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'l': + m_joint->EnableLimit(!m_joint->IsLimitEnabled()); + break; - case 'm': - m_joint->EnableMotor(!m_joint->IsMotorEnabled()); - break; + case 'm': + m_joint->EnableMotor(!m_joint->IsMotorEnabled()); + break; - case 's': - m_joint->SetMotorSpeed(-m_joint->GetMotorSpeed()); - break; - } - } + case 's': + m_joint->SetMotorSpeed(-m_joint->GetMotorSpeed()); + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motors, (s) speed"); - m_textLine += 15; - float32 force = m_joint->GetMotorForce(settings->hz); - m_debugDraw.DrawString(5, m_textLine, "Motor Force = %4.0f", (float) force); - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motors, (s) speed"); + m_textLine += DRAW_STRING_NEW_LINE; + float32 force = m_joint->GetMotorForce(settings->hz); + m_debugDraw.DrawString(5, m_textLine, "Motor Force = %4.0f", (float) force); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Prismatic; - } + static Test* Create() + { + return new Prismatic; + } - b2PrismaticJoint* m_joint; + b2PrismaticJoint* m_joint; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h index 7c961d25ca..ad5dd8ce39 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h @@ -22,85 +22,85 @@ class Pulleys : public Test { public: - Pulleys() - { - float32 y = 16.0f; - float32 L = 12.0f; - float32 a = 1.0f; - float32 b = 2.0f; + Pulleys() + { + float32 y = 16.0f; + float32 L = 12.0f; + float32 a = 1.0f; + float32 b = 2.0f; - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape edge; - edge.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - //ground->CreateFixture(&shape, 0.0f); + b2EdgeShape edge; + edge.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + //ground->CreateFixture(&shape, 0.0f); - b2CircleShape circle; - circle.m_radius = 2.0f; + b2CircleShape circle; + circle.m_radius = 2.0f; - circle.m_p.Set(-10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); + circle.m_p.Set(-10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); - circle.m_p.Set(10.0f, y + b + L); - ground->CreateFixture(&circle, 0.0f); - } + circle.m_p.Set(10.0f, y + b + L); + ground->CreateFixture(&circle, 0.0f); + } - { + { - b2PolygonShape shape; - shape.SetAsBox(a, b); + b2PolygonShape shape; + shape.SetAsBox(a, b); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - //bd.fixedRotation = true; - bd.position.Set(-10.0f, y); - b2Body* body1 = m_world->CreateBody(&bd); - body1->CreateFixture(&shape, 5.0f); + //bd.fixedRotation = true; + bd.position.Set(-10.0f, y); + b2Body* body1 = m_world->CreateBody(&bd); + body1->CreateFixture(&shape, 5.0f); - bd.position.Set(10.0f, y); - b2Body* body2 = m_world->CreateBody(&bd); - body2->CreateFixture(&shape, 5.0f); + bd.position.Set(10.0f, y); + b2Body* body2 = m_world->CreateBody(&bd); + body2->CreateFixture(&shape, 5.0f); - b2PulleyJointDef pulleyDef; - b2Vec2 anchor1(-10.0f, y + b); - b2Vec2 anchor2(10.0f, y + b); - b2Vec2 groundAnchor1(-10.0f, y + b + L); - b2Vec2 groundAnchor2(10.0f, y + b + L); - pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); + b2PulleyJointDef pulleyDef; + b2Vec2 anchor1(-10.0f, y + b); + b2Vec2 anchor2(10.0f, y + b); + b2Vec2 groundAnchor1(-10.0f, y + b + L); + b2Vec2 groundAnchor2(10.0f, y + b + L); + pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f); - m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); - } - } + m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 0: - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case 0: + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - float32 ratio = m_joint1->GetRatio(); - float32 L = m_joint1->GetLengthA() + ratio * m_joint1->GetLengthB(); - m_debugDraw.DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float) ratio, (float) L); - m_textLine += 15; - } + float32 ratio = m_joint1->GetRatio(); + float32 L = m_joint1->GetCurrentLengthA() + ratio * m_joint1->GetCurrentLengthB(); + m_debugDraw.DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (float) ratio, (float) L); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Pulleys; - } + static Test* Create() + { + return new Pulleys; + } - b2PulleyJoint* m_joint1; + b2PulleyJoint* m_joint1; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h index c6092e3e28..b52322ef01 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h @@ -22,68 +22,68 @@ class Pyramid : public Test { public: - enum - { - e_count = 20 - }; + enum + { + e_count = 20 + }; - Pyramid() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + Pyramid() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - float32 a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); + { + float32 a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); - for (int32 i = 0; i < e_count; ++i) - { - y = x; + for (int32 i = 0; i < e_count; ++i) + { + y = x; - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - y += deltaY; - } + y += deltaY; + } - x += deltaX; - } - } - } + x += deltaX; + } + } + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - //if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - //} - } + //if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + //} + } - static Test* Create() - { - return new Pyramid; - } + static Test* Create() + { + return new Pyramid; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h index 1749ff04a7..89d0bd06e2 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h @@ -27,118 +27,131 @@ class RayCastClosestCallback : public b2RayCastCallback { public: - RayCastClosestCallback() - { - m_hit = false; - } + RayCastClosestCallback() + { + m_hit = false; + } - float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) - { - b2Body* body = fixture->GetBody(); - void* userData = body->GetUserData(); - if (userData) - { - int32 index = *(int32*)userData; - if (index == 0) - { - // filter - return -1.0f; - } - } + float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) + { + b2Body* body = fixture->GetBody(); + void* userData = body->GetUserData(); + if (userData) + { + int32 index = *(int32*)userData; + if (index == 0) + { + // By returning -1, we instruct the calling code to ignore this fixture and + // continue the ray-cast to the next fixture. + return -1.0f; + } + } - m_hit = true; - m_point = point; - m_normal = normal; - return fraction; - } - - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + m_hit = true; + m_point = point; + m_normal = normal; + + // By returning the current fraction, we instruct the calling code to clip the ray and + // continue the ray-cast to the next fixture. WARNING: do not assume that fixtures + // are reported in order. However, by clipping, we can always get the closest fixture. + return fraction; + } + + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; -// This callback finds any hit. Polygon 0 is filtered. +// This callback finds any hit. Polygon 0 is filtered. For this type of query we are usually +// just checking for obstruction, so the actual fixture and hit point are irrelevant. class RayCastAnyCallback : public b2RayCastCallback { public: - RayCastAnyCallback() - { - m_hit = false; - } + RayCastAnyCallback() + { + m_hit = false; + } - float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) - { - b2Body* body = fixture->GetBody(); - void* userData = body->GetUserData(); - if (userData) - { - int32 index = *(int32*)userData; - if (index == 0) - { - // filter - return -1.0f; - } - } + float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) + { + b2Body* body = fixture->GetBody(); + void* userData = body->GetUserData(); + if (userData) + { + int32 index = *(int32*)userData; + if (index == 0) + { + // By returning -1, we instruct the calling code to ignore this fixture + // and continue the ray-cast to the next fixture. + return -1.0f; + } + } - m_hit = true; - m_point = point; - m_normal = normal; - return 0.0f; - } + m_hit = true; + m_point = point; + m_normal = normal; - bool m_hit; - b2Vec2 m_point; - b2Vec2 m_normal; + // At this point we have a hit, so we know the ray is obstructed. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } + + bool m_hit; + b2Vec2 m_point; + b2Vec2 m_normal; }; // This ray cast collects multiple hits along the ray. Polygon 0 is filtered. +// The fixtures are not necessary reported in order, so we might not capture +// the closest fixture. class RayCastMultipleCallback : public b2RayCastCallback { public: - enum - { - e_maxCount = 3 - }; + enum + { + e_maxCount = 3 + }; - RayCastMultipleCallback() - { - m_count = 0; - } + RayCastMultipleCallback() + { + m_count = 0; + } - float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) - { - b2Body* body = fixture->GetBody(); - void* userData = body->GetUserData(); - if (userData) - { - int32 index = *(int32*)userData; - if (index == 0) - { - // filter - return -1.0f; - } - } + float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) + { + b2Body* body = fixture->GetBody(); + void* userData = body->GetUserData(); + if (userData) + { + int32 index = *(int32*)userData; + if (index == 0) + { + // By returning -1, we instruct the calling code to ignore this fixture + // and continue the ray-cast to the next fixture. + return -1.0f; + } + } - b2Assert(m_count < e_maxCount); + b2Assert(m_count < e_maxCount); - m_points[m_count] = point; - m_normals[m_count] = normal; - ++m_count; + m_points[m_count] = point; + m_normals[m_count] = normal; + ++m_count; - if (m_count == e_maxCount) - { - return 0.0f; - } + if (m_count == e_maxCount) + { + // At this point the buffer is full. + // By returning 0, we instruct the calling code to terminate the ray-cast. + return 0.0f; + } - return 1.0f; - } + // By returning 1, we instruct the caller to continue without clipping the ray. + return 1.0f; + } - b2Vec2 m_points[e_maxCount]; - b2Vec2 m_normals[e_maxCount]; - int32 m_count; + b2Vec2 m_points[e_maxCount]; + b2Vec2 m_normals[e_maxCount]; + int32 m_count; }; @@ -146,295 +159,323 @@ class RayCast : public Test { public: - enum - { - e_maxBodies = 256 - }; + enum + { + e_maxBodies = 256 + }; - enum Mode - { - e_closest, - e_any, - e_multiple - }; + enum Mode + { + e_closest, + e_any, + e_multiple + }; - RayCast() - { - // Ground body - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + RayCast() + { + // Ground body + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.5f, 0.0f); - vertices[1].Set(0.5f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[0].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.5f, 0.0f); + vertices[1].Set(0.5f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[0].Set(vertices, 3); + } - { - b2Vec2 vertices[3]; - vertices[0].Set(-0.1f, 0.0f); - vertices[1].Set(0.1f, 0.0f); - vertices[2].Set(0.0f, 1.5f); - m_polygons[1].Set(vertices, 3); - } + { + b2Vec2 vertices[3]; + vertices[0].Set(-0.1f, 0.0f); + vertices[1].Set(0.1f, 0.0f); + vertices[2].Set(0.0f, 1.5f); + m_polygons[1].Set(vertices, 3); + } - { - float32 w = 1.0f; - float32 b = w / (2.0f + b2Sqrt(2.0f)); - float32 s = b2Sqrt(2.0f) * b; + { + float32 w = 1.0f; + float32 b = w / (2.0f + b2Sqrt(2.0f)); + float32 s = b2Sqrt(2.0f) * b; - b2Vec2 vertices[8]; - vertices[0].Set(0.5f * s, 0.0f); - vertices[1].Set(0.5f * w, b); - vertices[2].Set(0.5f * w, b + s); - vertices[3].Set(0.5f * s, w); - vertices[4].Set(-0.5f * s, w); - vertices[5].Set(-0.5f * w, b + s); - vertices[6].Set(-0.5f * w, b); - vertices[7].Set(-0.5f * s, 0.0f); + b2Vec2 vertices[8]; + vertices[0].Set(0.5f * s, 0.0f); + vertices[1].Set(0.5f * w, b); + vertices[2].Set(0.5f * w, b + s); + vertices[3].Set(0.5f * s, w); + vertices[4].Set(-0.5f * s, w); + vertices[5].Set(-0.5f * w, b + s); + vertices[6].Set(-0.5f * w, b); + vertices[7].Set(-0.5f * s, 0.0f); - m_polygons[2].Set(vertices, 8); - } + m_polygons[2].Set(vertices, 8); + } - { - m_polygons[3].SetAsBox(0.5f, 0.5f); - } + { + m_polygons[3].SetAsBox(0.5f, 0.5f); + } - { - m_circle.m_radius = 0.5f; - } + { + m_circle.m_radius = 0.5f; + } - m_bodyIndex = 0; - memset(m_bodies, 0, sizeof(m_bodies)); + { + m_edge.Set(b2Vec2(-1.0f, 0.0f), b2Vec2(1.0f, 0.0f)); + } - m_angle = 0.0f; + m_bodyIndex = 0; + memset(m_bodies, 0, sizeof(m_bodies)); - m_mode = e_closest; - } + m_angle = 0.0f; - void Create(int32 index) - { - if (m_bodies[m_bodyIndex] != NULL) - { - m_world->DestroyBody(m_bodies[m_bodyIndex]); - m_bodies[m_bodyIndex] = NULL; - } + m_mode = e_closest; + } - b2BodyDef bd; + void Create(int32 index) + { + if (m_bodies[m_bodyIndex] != NULL) + { + m_world->DestroyBody(m_bodies[m_bodyIndex]); + m_bodies[m_bodyIndex] = NULL; + } - float32 x = RandomFloat(-10.0f, 10.0f); - float32 y = RandomFloat(0.0f, 20.0f); - bd.position.Set(x, y); - bd.angle = RandomFloat(-b2_pi, b2_pi); + b2BodyDef bd; - m_userData[m_bodyIndex] = index; - bd.userData = m_userData + m_bodyIndex; + float32 x = RandomFloat(-10.0f, 10.0f); + float32 y = RandomFloat(0.0f, 20.0f); + bd.position.Set(x, y); + bd.angle = RandomFloat(-b2_pi, b2_pi); - if (index == 4) - { - bd.angularDamping = 0.02f; - } + m_userData[m_bodyIndex] = index; + bd.userData = m_userData + m_bodyIndex; - m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); + if (index == 4) + { + bd.angularDamping = 0.02f; + } - if (index < 4) - { - b2FixtureDef fd; - fd.shape = m_polygons + index; - fd.friction = 0.3f; - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } - else - { - b2FixtureDef fd; - fd.shape = &m_circle; - fd.friction = 0.3f; + m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); - m_bodies[m_bodyIndex]->CreateFixture(&fd); - } + if (index < 4) + { + b2FixtureDef fd; + fd.shape = m_polygons + index; + fd.friction = 0.3f; + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else if (index < 5) + { + b2FixtureDef fd; + fd.shape = &m_circle; + fd.friction = 0.3f; - m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; - } + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } + else + { + b2FixtureDef fd; + fd.shape = &m_edge; + fd.friction = 0.3f; - void DestroyBody() - { - for (int32 i = 0; i < e_maxBodies; ++i) - { - if (m_bodies[i] != NULL) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - return; - } - } - } + m_bodies[m_bodyIndex]->CreateFixture(&fd); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case '1': - case '2': - case '3': - case '4': - case '5': - Create(key - '1'); - break; + m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; + } - case 'd': - DestroyBody(); - break; + void DestroyBody() + { + for (int32 i = 0; i < e_maxBodies; ++i) + { + if (m_bodies[i] != NULL) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + return; + } + } + } - case 'm': - if (m_mode == e_closest) - { - m_mode = e_any; - } - else if (m_mode == e_any) - { - m_mode = e_multiple; - } - else if (m_mode == e_multiple) - { - m_mode = e_closest; - } - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + Create(key - '1'); + break; - void Step(Settings* settings) - { - bool advanceRay = settings->pause == 0 || settings->singleStep; + case 'd': + DestroyBody(); + break; - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff, m to change the mode"); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Mode = %d", m_mode); - m_textLine += 15; + case 'm': + if (m_mode == e_closest) + { + m_mode = e_any; + } + else if (m_mode == e_any) + { + m_mode = e_multiple; + } + else if (m_mode == e_multiple) + { + m_mode = e_closest; + } + } + } - float32 L = 11.0f; - b2Vec2 point1(0.0f, 10.0f); - b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle)); - b2Vec2 point2 = point1 + d; + void Step(Settings* settings) + { + bool advanceRay = settings->pause == 0 || settings->singleStep; - if (m_mode == e_closest) - { - RayCastClosestCallback callback; - m_world->RayCast(&callback, point1, point2); + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press 1-6 to drop stuff, m to change the mode"); + m_textLine += DRAW_STRING_NEW_LINE; + switch (m_mode) + { + case e_closest: + m_debugDraw.DrawString(5, m_textLine, "Ray-cast mode: closest - find closest fixture along the ray"); + break; + + case e_any: + m_debugDraw.DrawString(5, m_textLine, "Ray-cast mode: any - check for obstruction"); + break; - if (callback.m_hit) - { - m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_any) - { - RayCastAnyCallback callback; - m_world->RayCast(&callback, point1, point2); + case e_multiple: + m_debugDraw.DrawString(5, m_textLine, "Ray-cast mode: multiple - gather multiple fixtures"); + break; + } - if (callback.m_hit) - { - m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; - m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); - } - else - { - m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); - } - } - else if (m_mode == e_multiple) - { - RayCastMultipleCallback callback; - m_world->RayCast(&callback, point1, point2); - m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + m_textLine += DRAW_STRING_NEW_LINE; - for (int32 i = 0; i < callback.m_count; ++i) - { - b2Vec2 p = callback.m_points[i]; - b2Vec2 n = callback.m_normals[i]; - m_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); - m_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); - b2Vec2 head = p + 0.5f * n; - m_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); - } - } + float32 L = 11.0f; + b2Vec2 point1(0.0f, 10.0f); + b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle)); + b2Vec2 point2 = point1 + d; - if (advanceRay) - { - m_angle += 0.25f * b2_pi / 180.0f; - } + if (m_mode == e_closest) + { + RayCastClosestCallback callback; + m_world->RayCast(&callback, point1, point2); + + if (callback.m_hit) + { + m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_any) + { + RayCastAnyCallback callback; + m_world->RayCast(&callback, point1, point2); + + if (callback.m_hit) + { + m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; + m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); + } + else + { + m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + } + } + else if (m_mode == e_multiple) + { + RayCastMultipleCallback callback; + m_world->RayCast(&callback, point1, point2); + m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); + + for (int32 i = 0; i < callback.m_count; ++i) + { + b2Vec2 p = callback.m_points[i]; + b2Vec2 n = callback.m_normals[i]; + m_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); + m_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f)); + b2Vec2 head = p + 0.5f * n; + m_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f)); + } + } + + if (advanceRay) + { + m_angle += 0.25f * b2_pi / 180.0f; + } #if 0 - // This case was failing. - { - b2Vec2 vertices[4]; - //vertices[0].Set(-22.875f, -3.0f); - //vertices[1].Set(22.875f, -3.0f); - //vertices[2].Set(22.875f, 3.0f); - //vertices[3].Set(-22.875f, 3.0f); + // This case was failing. + { + b2Vec2 vertices[4]; + //vertices[0].Set(-22.875f, -3.0f); + //vertices[1].Set(22.875f, -3.0f); + //vertices[2].Set(22.875f, 3.0f); + //vertices[3].Set(-22.875f, 3.0f); - b2PolygonShape shape; - //shape.Set(vertices, 4); - shape.SetAsBox(22.875f, 3.0f); + b2PolygonShape shape; + //shape.Set(vertices, 4); + shape.SetAsBox(22.875f, 3.0f); - b2RayCastInput input; - input.p1.Set(10.2725f,1.71372f); - input.p2.Set(10.2353f,2.21807f); - //input.maxFraction = 0.567623f; - input.maxFraction = 0.56762173f; + b2RayCastInput input; + input.p1.Set(10.2725f,1.71372f); + input.p2.Set(10.2353f,2.21807f); + //input.maxFraction = 0.567623f; + input.maxFraction = 0.56762173f; - b2Transform xf; - xf.SetIdentity(); - xf.position.Set(23.0f, 5.0f); + b2Transform xf; + xf.SetIdentity(); + xf.position.Set(23.0f, 5.0f); - b2RayCastOutput output; - bool hit; - hit = shape.RayCast(&output, input, xf); - hit = false; + b2RayCastOutput output; + bool hit; + hit = shape.RayCast(&output, input, xf); + hit = false; - b2Color color(1.0f, 1.0f, 1.0f); - b2Vec2 vs[4]; - for (int32 i = 0; i < 4; ++i) - { - vs[i] = b2Mul(xf, shape.m_vertices[i]); - } + b2Color color(1.0f, 1.0f, 1.0f); + b2Vec2 vs[4]; + for (int32 i = 0; i < 4; ++i) + { + vs[i] = b2Mul(xf, shape.m_vertices[i]); + } - m_debugDraw.DrawPolygon(vs, 4, color); - m_debugDraw.DrawSegment(input.p1, input.p2, color); - } + m_debugDraw.DrawPolygon(vs, 4, color); + m_debugDraw.DrawSegment(input.p1, input.p2, color); + } #endif - } + } - static Test* Create() - { - return new RayCast; - } + static Test* Create() + { + return new RayCast; + } - int32 m_bodyIndex; - b2Body* m_bodies[e_maxBodies]; - int32 m_userData[e_maxBodies]; - b2PolygonShape m_polygons[4]; - b2CircleShape m_circle; + int32 m_bodyIndex; + b2Body* m_bodies[e_maxBodies]; + int32 m_userData[e_maxBodies]; + b2PolygonShape m_polygons[4]; + b2CircleShape m_circle; + b2EdgeShape m_edge; - float32 m_angle; + float32 m_angle; - Mode m_mode; + Mode m_mode; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h index 2e115d91a7..6501eb6cba 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h @@ -22,145 +22,145 @@ class Revolute : public Test { public: - Revolute() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Revolute() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - b2FixtureDef fd; - fd.shape = &shape; - //fd.filter.categoryBits = 2; + b2FixtureDef fd; + fd.shape = &shape; + //fd.filter.categoryBits = 2; - ground->CreateFixture(&fd); - } + ground->CreateFixture(&fd); + } - { - b2CircleShape shape; - shape.m_radius = 0.5f; + { + b2CircleShape shape; + shape.m_radius = 0.5f; - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - b2RevoluteJointDef rjd; + b2RevoluteJointDef rjd; - bd.position.Set(-10.0f, 20.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); + bd.position.Set(-10.0f, 20.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); - float32 w = 100.0f; - body->SetAngularVelocity(w); - body->SetLinearVelocity(b2Vec2(-8.0f * w, 0.0f)); + float32 w = 100.0f; + body->SetAngularVelocity(w); + body->SetLinearVelocity(b2Vec2(-8.0f * w, 0.0f)); - rjd.Initialize(ground, body, b2Vec2(-10.0f, 12.0f)); - rjd.motorSpeed = 1.0f * b2_pi; - rjd.maxMotorTorque = 10000.0f; - rjd.enableMotor = false; - rjd.lowerAngle = -0.25f * b2_pi; - rjd.upperAngle = 0.5f * b2_pi; - rjd.enableLimit = true; - rjd.collideConnected = true; + rjd.Initialize(ground, body, b2Vec2(-10.0f, 12.0f)); + rjd.motorSpeed = 1.0f * b2_pi; + rjd.maxMotorTorque = 10000.0f; + rjd.enableMotor = false; + rjd.lowerAngle = -0.25f * b2_pi; + rjd.upperAngle = 0.5f * b2_pi; + rjd.enableLimit = true; + rjd.collideConnected = true; - m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); - } + m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); + } - { - b2CircleShape circle_shape; - circle_shape.m_radius = 3.0f; + { + b2CircleShape circle_shape; + circle_shape.m_radius = 3.0f; - b2BodyDef circle_bd; - circle_bd.type = b2_dynamicBody; - circle_bd.position.Set(5.0f, 30.0f); + b2BodyDef circle_bd; + circle_bd.type = b2_dynamicBody; + circle_bd.position.Set(5.0f, 30.0f); - b2FixtureDef fd; - fd.density = 5.0f; - fd.filter.maskBits = 1; - fd.shape = &circle_shape; + b2FixtureDef fd; + fd.density = 5.0f; + fd.filter.maskBits = 1; + fd.shape = &circle_shape; - m_ball = m_world->CreateBody(&circle_bd); - m_ball->CreateFixture(&fd); + m_ball = m_world->CreateBody(&circle_bd); + m_ball->CreateFixture(&fd); - b2PolygonShape polygon_shape; - polygon_shape.SetAsBox(10.0f, 0.2f, b2Vec2 (-10.0f, 0.0f), 0.0f); + b2PolygonShape polygon_shape; + polygon_shape.SetAsBox(10.0f, 0.2f, b2Vec2 (-10.0f, 0.0f), 0.0f); - b2BodyDef polygon_bd; - polygon_bd.position.Set(20.0f, 10.0f); - polygon_bd.type = b2_dynamicBody; - polygon_bd.bullet = true; - b2Body* polygon_body = m_world->CreateBody(&polygon_bd); - polygon_body->CreateFixture(&polygon_shape, 2.0f); + b2BodyDef polygon_bd; + polygon_bd.position.Set(20.0f, 10.0f); + polygon_bd.type = b2_dynamicBody; + polygon_bd.bullet = true; + b2Body* polygon_body = m_world->CreateBody(&polygon_bd); + polygon_body->CreateFixture(&polygon_shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(ground, polygon_body, b2Vec2(20.0f, 10.0f)); - rjd.lowerAngle = -0.25f * b2_pi; - rjd.upperAngle = 0.0f * b2_pi; - rjd.enableLimit = true; - m_world->CreateJoint(&rjd); - } + b2RevoluteJointDef rjd; + rjd.Initialize(ground, polygon_body, b2Vec2(20.0f, 10.0f)); + rjd.lowerAngle = -0.25f * b2_pi; + rjd.upperAngle = 0.0f * b2_pi; + rjd.enableLimit = true; + m_world->CreateJoint(&rjd); + } - // Tests mass computation of a small object far from the origin - { - b2BodyDef bodyDef; - bodyDef.type = b2_dynamicBody; - b2Body* body = m_world->CreateBody(&bodyDef); - - b2PolygonShape polyShape; - b2Vec2 verts[3]; - verts[0].Set( 17.63f, 36.31f ); - verts[1].Set( 17.52f, 36.69f ); - verts[2].Set( 17.19f, 36.36f ); - polyShape.Set(verts, 3); - - b2FixtureDef polyFixtureDef; - polyFixtureDef.shape = &polyShape; - polyFixtureDef.density = 1; + // Tests mass computation of a small object far from the origin + { + b2BodyDef bodyDef; + bodyDef.type = b2_dynamicBody; + b2Body* body = m_world->CreateBody(&bodyDef); + + b2PolygonShape polyShape; + b2Vec2 verts[3]; + verts[0].Set( 17.63f, 36.31f ); + verts[1].Set( 17.52f, 36.69f ); + verts[2].Set( 17.19f, 36.36f ); + polyShape.Set(verts, 3); + + b2FixtureDef polyFixtureDef; + polyFixtureDef.shape = &polyShape; + polyFixtureDef.density = 1; - body->CreateFixture(&polyFixtureDef); //assertion hits inside here - } + body->CreateFixture(&polyFixtureDef); //assertion hits inside here + } - } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'l': - m_joint->EnableLimit(!m_joint->IsLimitEnabled()); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'l': + m_joint->EnableLimit(!m_joint->IsLimitEnabled()); + break; - case 'm': - m_joint->EnableMotor(!m_joint->IsMotorEnabled()); - break; - } - } + case 'm': + m_joint->EnableMotor(!m_joint->IsMotorEnabled()); + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motor"); - m_textLine += 15; + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motor"); + m_textLine += DRAW_STRING_NEW_LINE; - //if (m_stepCount == 360) - //{ - // m_ball->SetTransform(b2Vec2(0.0f, 0.5f), 0.0f); - //} + //if (m_stepCount == 360) + //{ + // m_ball->SetTransform(b2Vec2(0.0f, 0.5f), 0.0f); + //} - //float32 torque1 = m_joint1->GetMotorTorque(); - //m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %4.0f, %4.0f : Motor Force = %4.0f", (float) torque1, (float) torque2, (float) force3); - //m_textLine += 15; - } + //float32 torque1 = m_joint1->GetMotorTorque(); + //m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %4.0f, %4.0f : Motor Force = %4.0f", (float) torque1, (float) torque2, (float) force3); + //m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Revolute; - } + static Test* Create() + { + return new Revolute; + } - b2Body* m_ball; - b2RevoluteJoint* m_joint; + b2Body* m_ball; + b2RevoluteJoint* m_joint; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h index 5869387dc8..b479134e94 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h @@ -23,79 +23,79 @@ class Rope : public Test { public: - Rope() - { - const int32 N = 40; - b2Vec2 vertices[N]; - float32 masses[N]; + Rope() + { + const int32 N = 40; + b2Vec2 vertices[N]; + float32 masses[N]; - for (int32 i = 0; i < N; ++i) - { - vertices[i].Set(0.0f, 20.0f - 0.25f * i); - masses[i] = 1.0f; - } - masses[0] = 0.0f; - masses[1] = 0.0f; + for (int32 i = 0; i < N; ++i) + { + vertices[i].Set(0.0f, 20.0f - 0.25f * i); + masses[i] = 1.0f; + } + masses[0] = 0.0f; + masses[1] = 0.0f; - b2RopeDef def; - def.vertices = vertices; - def.count = N; - def.gravity.Set(0.0f, -10.0f); - def.masses = masses; - def.damping = 0.1f; - def.k2 = 1.0f; - def.k3 = 0.5f; + b2RopeDef def; + def.vertices = vertices; + def.count = N; + def.gravity.Set(0.0f, -10.0f); + def.masses = masses; + def.damping = 0.1f; + def.k2 = 1.0f; + def.k3 = 0.5f; - m_rope.Initialize(&def); + m_rope.Initialize(&def); - m_angle = 0.0f; - m_rope.SetAngle(m_angle); - } + m_angle = 0.0f; + m_rope.SetAngle(m_angle); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'q': - m_angle = b2Max(-b2_pi, m_angle - 0.05f * b2_pi); - m_rope.SetAngle(m_angle); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'q': + m_angle = b2Max(-b2_pi, m_angle - 0.05f * b2_pi); + m_rope.SetAngle(m_angle); + break; - case 'e': - m_angle = b2Min(b2_pi, m_angle + 0.05f * b2_pi); - m_rope.SetAngle(m_angle); - break; - } - } + case 'e': + m_angle = b2Min(b2_pi, m_angle + 0.05f * b2_pi); + m_rope.SetAngle(m_angle); + break; + } + } - void Step(Settings* settings) - { - float32 dt = settings->hz > 0.0f ? 1.0f / settings->hz : 0.0f; + void Step(Settings* settings) + { + float32 dt = settings->hz > 0.0f ? 1.0f / settings->hz : 0.0f; - if (settings->pause == 1 && settings->singleStep == 0) - { - dt = 0.0f; - } + if (settings->pause == 1 && settings->singleStep == 0) + { + dt = 0.0f; + } - m_rope.Step(dt, 1); + m_rope.Step(dt, 1); - Test::Step(settings); + Test::Step(settings); - m_rope.Draw(&m_debugDraw); + m_rope.Draw(&m_debugDraw); - m_debugDraw.DrawString(5, m_textLine, "Press (q,e) to adjust target angle"); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Target angle = %g degrees", m_angle * 180.0f / b2_pi); - m_textLine += 15; - } + m_debugDraw.DrawString(5, m_textLine, "Press (q,e) to adjust target angle"); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Target angle = %g degrees", m_angle * 180.0f / b2_pi); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new Rope; - } + static Test* Create() + { + return new Rope; + } - b2Rope m_rope; - float32 m_angle; + b2Rope m_rope; + float32 m_angle; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h index 14e5018a25..a8b935201a 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h @@ -30,116 +30,116 @@ class RopeJoint : public Test { public: - RopeJoint() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + RopeJoint() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.125f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.125f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.friction = 0.2f; - fd.filter.categoryBits = 0x0001; - fd.filter.maskBits = 0xFFFF & ~0x0002; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.friction = 0.2f; + fd.filter.categoryBits = 0x0001; + fd.filter.maskBits = 0xFFFF & ~0x0002; - b2RevoluteJointDef jd; - jd.collideConnected = false; + b2RevoluteJointDef jd; + jd.collideConnected = false; - const int32 N = 10; - const float32 y = 15.0f; - m_ropeDef.localAnchorA.Set(0.0f, y); + const int32 N = 10; + const float32 y = 15.0f; + m_ropeDef.localAnchorA.Set(0.0f, y); - b2Body* prevBody = ground; - for (int32 i = 0; i < N; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.5f + 1.0f * i, y); - if (i == N - 1) - { - shape.SetAsBox(1.5f, 1.5f); - fd.density = 100.0f; - fd.filter.categoryBits = 0x0002; - bd.position.Set(1.0f * i, y); - bd.angularDamping = 0.4f; - } + b2Body* prevBody = ground; + for (int32 i = 0; i < N; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.5f + 1.0f * i, y); + if (i == N - 1) + { + shape.SetAsBox(1.5f, 1.5f); + fd.density = 100.0f; + fd.filter.categoryBits = 0x0002; + bd.position.Set(1.0f * i, y); + bd.angularDamping = 0.4f; + } - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&fd); + body->CreateFixture(&fd); - b2Vec2 anchor(float32(i), y); - jd.Initialize(prevBody, body, anchor); - m_world->CreateJoint(&jd); + b2Vec2 anchor(float32(i), y); + jd.Initialize(prevBody, body, anchor); + m_world->CreateJoint(&jd); - prevBody = body; - } + prevBody = body; + } - m_ropeDef.localAnchorB.SetZero(); + m_ropeDef.localAnchorB.SetZero(); - float32 extraLength = 0.01f; - m_ropeDef.maxLength = N - 1.0f + extraLength; - m_ropeDef.bodyB = prevBody; - } + float32 extraLength = 0.01f; + m_ropeDef.maxLength = N - 1.0f + extraLength; + m_ropeDef.bodyB = prevBody; + } - { - m_ropeDef.bodyA = ground; - m_rope = m_world->CreateJoint(&m_ropeDef); - } - } + { + m_ropeDef.bodyA = ground; + m_rope = m_world->CreateJoint(&m_ropeDef); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'j': - if (m_rope) - { - m_world->DestroyJoint(m_rope); - m_rope = NULL; - } - else - { - m_rope = m_world->CreateJoint(&m_ropeDef); - } - break; - } - } + void Keyboard(unsigned char key) + { + switch (key) + { + case 'j': + if (m_rope) + { + m_world->DestroyJoint(m_rope); + m_rope = NULL; + } + else + { + m_rope = m_world->CreateJoint(&m_ropeDef); + } + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press (j) to toggle the rope joint."); - m_textLine += 15; - if (m_rope) - { - m_debugDraw.DrawString(5, m_textLine, "Rope ON"); - } - else - { - m_debugDraw.DrawString(5, m_textLine, "Rope OFF"); - } - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press (j) to toggle the rope joint."); + m_textLine += DRAW_STRING_NEW_LINE; + if (m_rope) + { + m_debugDraw.DrawString(5, m_textLine, "Rope ON"); + } + else + { + m_debugDraw.DrawString(5, m_textLine, "Rope OFF"); + } + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new RopeJoint; - } + static Test* Create() + { + return new RopeJoint; + } - b2RopeJointDef m_ropeDef; - b2Joint* m_rope; + b2RopeJointDef m_ropeDef; + b2Joint* m_rope; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h index a7c74b5e93..f15cd7714e 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h @@ -24,158 +24,158 @@ class SensorTest : public Test { public: - enum - { - e_count = 7 - }; + enum + { + e_count = 7 + }; - SensorTest() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + SensorTest() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - { - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + { + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } #if 0 - { - b2FixtureDef sd; - sd.SetAsBox(10.0f, 2.0f, b2Vec2(0.0f, 20.0f), 0.0f); - sd.isSensor = true; - m_sensor = ground->CreateFixture(&sd); - } + { + b2FixtureDef sd; + sd.SetAsBox(10.0f, 2.0f, b2Vec2(0.0f, 20.0f), 0.0f); + sd.isSensor = true; + m_sensor = ground->CreateFixture(&sd); + } #else - { - b2CircleShape shape; - shape.m_radius = 5.0f; - shape.m_p.Set(0.0f, 10.0f); + { + b2CircleShape shape; + shape.m_radius = 5.0f; + shape.m_p.Set(0.0f, 10.0f); - b2FixtureDef fd; - fd.shape = &shape; - fd.isSensor = true; - m_sensor = ground->CreateFixture(&fd); - } + b2FixtureDef fd; + fd.shape = &shape; + fd.isSensor = true; + m_sensor = ground->CreateFixture(&fd); + } #endif - } + } - { - b2CircleShape shape; - shape.m_radius = 1.0f; + { + b2CircleShape shape; + shape.m_radius = 1.0f; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); - bd.userData = m_touching + i; + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); + bd.userData = m_touching + i; - m_touching[i] = false; - m_bodies[i] = m_world->CreateBody(&bd); + m_touching[i] = false; + m_bodies[i] = m_world->CreateBody(&bd); - m_bodies[i]->CreateFixture(&shape, 1.0f); - } - } - } + m_bodies[i]->CreateFixture(&shape, 1.0f); + } + } + } - // Implement contact listener. - void BeginContact(b2Contact* contact) - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + // Implement contact listener. + void BeginContact(b2Contact* contact) + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == m_sensor) - { - void* userData = fixtureB->GetBody()->GetUserData(); - if (userData) - { - bool* touching = (bool*)userData; - *touching = true; - } - } + if (fixtureA == m_sensor) + { + void* userData = fixtureB->GetBody()->GetUserData(); + if (userData) + { + bool* touching = (bool*)userData; + *touching = true; + } + } - if (fixtureB == m_sensor) - { - void* userData = fixtureA->GetBody()->GetUserData(); - if (userData) - { - bool* touching = (bool*)userData; - *touching = true; - } - } - } + if (fixtureB == m_sensor) + { + void* userData = fixtureA->GetBody()->GetUserData(); + if (userData) + { + bool* touching = (bool*)userData; + *touching = true; + } + } + } - // Implement contact listener. - void EndContact(b2Contact* contact) - { - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); + // Implement contact listener. + void EndContact(b2Contact* contact) + { + b2Fixture* fixtureA = contact->GetFixtureA(); + b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == m_sensor) - { - void* userData = fixtureB->GetBody()->GetUserData(); - if (userData) - { - bool* touching = (bool*)userData; - *touching = false; - } - } + if (fixtureA == m_sensor) + { + void* userData = fixtureB->GetBody()->GetUserData(); + if (userData) + { + bool* touching = (bool*)userData; + *touching = false; + } + } - if (fixtureB == m_sensor) - { - void* userData = fixtureA->GetBody()->GetUserData(); - if (userData) - { - bool* touching = (bool*)userData; - *touching = false; - } - } - } + if (fixtureB == m_sensor) + { + void* userData = fixtureA->GetBody()->GetUserData(); + if (userData) + { + bool* touching = (bool*)userData; + *touching = false; + } + } + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - // Traverse the contact results. Apply a force on shapes - // that overlap the sensor. - for (int32 i = 0; i < e_count; ++i) - { - if (m_touching[i] == false) - { - continue; - } + // Traverse the contact results. Apply a force on shapes + // that overlap the sensor. + for (int32 i = 0; i < e_count; ++i) + { + if (m_touching[i] == false) + { + continue; + } - b2Body* body = m_bodies[i]; - b2Body* ground = m_sensor->GetBody(); + b2Body* body = m_bodies[i]; + b2Body* ground = m_sensor->GetBody(); - b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); - b2Vec2 center = ground->GetWorldPoint(circle->m_p); + b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape(); + b2Vec2 center = ground->GetWorldPoint(circle->m_p); - b2Vec2 position = body->GetPosition(); + b2Vec2 position = body->GetPosition(); - b2Vec2 d = center - position; - if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) - { - continue; - } + b2Vec2 d = center - position; + if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) + { + continue; + } - d.Normalize(); - b2Vec2 F = 100.0f * d; - body->ApplyForce(F, position); - } - } + d.Normalize(); + b2Vec2 F = 100.0f * d; + body->ApplyForce(F, position, false); + } + } - static Test* Create() - { - return new SensorTest; - } + static Test* Create() + { + return new SensorTest; + } - b2Fixture* m_sensor; - b2Body* m_bodies[e_count]; - bool m_touching[e_count]; + b2Fixture* m_sensor; + b2Body* m_bodies[e_count]; + bool m_touching[e_count]; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h index 666190ab11..5cea181793 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h @@ -23,83 +23,83 @@ class ShapeEditing : public Test { public: - ShapeEditing() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + ShapeEditing() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - m_body = m_world->CreateBody(&bd); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + m_body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); - m_fixture1 = m_body->CreateFixture(&shape, 10.0f); + b2PolygonShape shape; + shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); + m_fixture1 = m_body->CreateFixture(&shape, 10.0f); - m_fixture2 = NULL; + m_fixture2 = NULL; - m_sensor = false; - } + m_sensor = false; + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'c': - if (m_fixture2 == NULL) - { - b2CircleShape shape; - shape.m_radius = 3.0f; - shape.m_p.Set(0.5f, -4.0f); - m_fixture2 = m_body->CreateFixture(&shape, 10.0f); - m_body->SetAwake(true); - } - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'c': + if (m_fixture2 == NULL) + { + b2CircleShape shape; + shape.m_radius = 3.0f; + shape.m_p.Set(0.5f, -4.0f); + m_fixture2 = m_body->CreateFixture(&shape, 10.0f); + m_body->SetAwake(true); + } + break; - case 'd': - if (m_fixture2 != NULL) - { - m_body->DestroyFixture(m_fixture2); - m_fixture2 = NULL; - m_body->SetAwake(true); - } - break; + case 'd': + if (m_fixture2 != NULL) + { + m_body->DestroyFixture(m_fixture2); + m_fixture2 = NULL; + m_body->SetAwake(true); + } + break; - case 's': - if (m_fixture2 != NULL) - { - m_sensor = !m_sensor; - m_fixture2->SetSensor(m_sensor); - } - break; - } - } + case 's': + if (m_fixture2 != NULL) + { + m_sensor = !m_sensor; + m_fixture2->SetSensor(m_sensor); + } + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "sensor = %d", m_sensor); - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (d) destroy a shape."); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "sensor = %d", m_sensor); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new ShapeEditing; - } + static Test* Create() + { + return new ShapeEditing; + } - b2Body* m_body; - b2Fixture* m_fixture1; - b2Fixture* m_fixture2; - bool m_sensor; + b2Body* m_body; + b2Fixture* m_fixture1; + b2Fixture* m_fixture2; + bool m_sensor; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h index 5de76acc0f..7d914d7eed 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h @@ -24,133 +24,133 @@ class SliderCrank : public Test { public: - SliderCrank() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + SliderCrank() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2Body* prevBody = ground; + { + b2Body* prevBody = ground; - // Define crank. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 2.0f); + // Define crank. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 2.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 7.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 7.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); - rjd.motorSpeed = 1.0f * b2_pi; - rjd.maxMotorTorque = 10000.0f; - rjd.enableMotor = true; - m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f)); + rjd.motorSpeed = 1.0f * b2_pi; + rjd.maxMotorTorque = 10000.0f; + rjd.enableMotor = true; + m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd); - prevBody = body; - } + prevBody = body; + } - // Define follower. - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 4.0f); + // Define follower. + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 4.0f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 13.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 13.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); - rjd.enableMotor = false; - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f)); + rjd.enableMotor = false; + m_world->CreateJoint(&rjd); - prevBody = body; - } + prevBody = body; + } - // Define piston - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); + // Define piston + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.fixedRotation = true; - bd.position.Set(0.0f, 17.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.fixedRotation = true; + bd.position.Set(0.0f, 17.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); - b2RevoluteJointDef rjd; - rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); - m_world->CreateJoint(&rjd); + b2RevoluteJointDef rjd; + rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f)); + m_world->CreateJoint(&rjd); - b2PrismaticJointDef pjd; - pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); + b2PrismaticJointDef pjd; + pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.0f, 1.0f)); - pjd.maxMotorForce = 1000.0f; - pjd.enableMotor = true; + pjd.maxMotorForce = 1000.0f; + pjd.enableMotor = true; - m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); - } + m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd); + } - // Create a payload - { - b2PolygonShape shape; - shape.SetAsBox(1.5f, 1.5f); + // Create a payload + { + b2PolygonShape shape; + shape.SetAsBox(1.5f, 1.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 23.0f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 2.0f); - } - } - } + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 23.0f); + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 2.0f); + } + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'f': - m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); - m_joint2->GetBodyB()->SetAwake(true); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'f': + m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); + m_joint2->GetBodyB()->SetAwake(true); + break; - case 'm': - m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); - m_joint1->GetBodyB()->SetAwake(true); - break; - } - } + case 'm': + m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); + m_joint1->GetBodyB()->SetAwake(true); + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); - m_textLine += 15; - float32 torque = m_joint1->GetMotorTorque(settings->hz); - m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %5.0f", (float) torque); - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Keys: (f) toggle friction, (m) toggle motor"); + m_textLine += DRAW_STRING_NEW_LINE; + float32 torque = m_joint1->GetMotorTorque(settings->hz); + m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %5.0f", (float) torque); + m_textLine += DRAW_STRING_NEW_LINE; + } - static Test* Create() - { - return new SliderCrank; - } + static Test* Create() + { + return new SliderCrank; + } - b2RevoluteJoint* m_joint1; - b2PrismaticJoint* m_joint2; + b2RevoluteJoint* m_joint1; + b2PrismaticJoint* m_joint2; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h index 88f1346d20..2948cbfd48 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h @@ -23,64 +23,64 @@ class SphereStack : public Test { public: - enum - { - e_count = 10 - }; + enum + { + e_count = 10 + }; - SphereStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + SphereStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2CircleShape shape; - shape.m_radius = 1.0f; + { + b2CircleShape shape; + shape.m_radius = 1.0f; - for (int32 i = 0; i < e_count; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0, 4.0f + 3.0f * i); + for (int32 i = 0; i < e_count; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0, 4.0f + 3.0f * i); - m_bodies[i] = m_world->CreateBody(&bd); + m_bodies[i] = m_world->CreateBody(&bd); - m_bodies[i]->CreateFixture(&shape, 1.0f); + m_bodies[i]->CreateFixture(&shape, 1.0f); - m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); - } - } - } + m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); + } + } + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - //for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetWorldCenter().y); - //} + //for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetWorldCenter().y); + //} - //for (int32 i = 0; i < e_count; ++i) - //{ - // printf("%g ", m_bodies[i]->GetLinearVelocity().y); - //} + //for (int32 i = 0; i < e_count; ++i) + //{ + // printf("%g ", m_bodies[i]->GetLinearVelocity().y); + //} - //printf("\n"); - } + //printf("\n"); + } - static Test* Create() - { - return new SphereStack; - } + static Test* Create() + { + return new SphereStack; + } - b2Body* m_bodies[e_count]; + b2Body* m_bodies[e_count]; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h index b0df0dea8f..f884d68176 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h @@ -26,231 +26,231 @@ class TheoJansen : public Test { public: - void CreateLeg(float32 s, const b2Vec2& wheelAnchor) - { - b2Vec2 p1(5.4f * s, -6.1f); - b2Vec2 p2(7.2f * s, -1.2f); - b2Vec2 p3(4.3f * s, -1.9f); - b2Vec2 p4(3.1f * s, 0.8f); - b2Vec2 p5(6.0f * s, 1.5f); - b2Vec2 p6(2.5f * s, 3.7f); + void CreateLeg(float32 s, const b2Vec2& wheelAnchor) + { + b2Vec2 p1(5.4f * s, -6.1f); + b2Vec2 p2(7.2f * s, -1.2f); + b2Vec2 p3(4.3f * s, -1.9f); + b2Vec2 p4(3.1f * s, 0.8f); + b2Vec2 p5(6.0f * s, 1.5f); + b2Vec2 p6(2.5f * s, 3.7f); - b2FixtureDef fd1, fd2; - fd1.filter.groupIndex = -1; - fd2.filter.groupIndex = -1; - fd1.density = 1.0f; - fd2.density = 1.0f; + b2FixtureDef fd1, fd2; + fd1.filter.groupIndex = -1; + fd2.filter.groupIndex = -1; + fd1.density = 1.0f; + fd2.density = 1.0f; - b2PolygonShape poly1, poly2; + b2PolygonShape poly1, poly2; - if (s > 0.0f) - { - b2Vec2 vertices[3]; + if (s > 0.0f) + { + b2Vec2 vertices[3]; - vertices[0] = p1; - vertices[1] = p2; - vertices[2] = p3; - poly1.Set(vertices, 3); + vertices[0] = p1; + vertices[1] = p2; + vertices[2] = p3; + poly1.Set(vertices, 3); - vertices[0] = b2Vec2_zero; - vertices[1] = p5 - p4; - vertices[2] = p6 - p4; - poly2.Set(vertices, 3); - } - else - { - b2Vec2 vertices[3]; + vertices[0] = b2Vec2_zero; + vertices[1] = p5 - p4; + vertices[2] = p6 - p4; + poly2.Set(vertices, 3); + } + else + { + b2Vec2 vertices[3]; - vertices[0] = p1; - vertices[1] = p3; - vertices[2] = p2; - poly1.Set(vertices, 3); + vertices[0] = p1; + vertices[1] = p3; + vertices[2] = p2; + poly1.Set(vertices, 3); - vertices[0] = b2Vec2_zero; - vertices[1] = p6 - p4; - vertices[2] = p5 - p4; - poly2.Set(vertices, 3); - } + vertices[0] = b2Vec2_zero; + vertices[1] = p6 - p4; + vertices[2] = p5 - p4; + poly2.Set(vertices, 3); + } - fd1.shape = &poly1; - fd2.shape = &poly2; + fd1.shape = &poly1; + fd2.shape = &poly2; - b2BodyDef bd1, bd2; - bd1.type = b2_dynamicBody; - bd2.type = b2_dynamicBody; - bd1.position = m_offset; - bd2.position = p4 + m_offset; + b2BodyDef bd1, bd2; + bd1.type = b2_dynamicBody; + bd2.type = b2_dynamicBody; + bd1.position = m_offset; + bd2.position = p4 + m_offset; - bd1.angularDamping = 10.0f; - bd2.angularDamping = 10.0f; + bd1.angularDamping = 10.0f; + bd2.angularDamping = 10.0f; - b2Body* body1 = m_world->CreateBody(&bd1); - b2Body* body2 = m_world->CreateBody(&bd2); + b2Body* body1 = m_world->CreateBody(&bd1); + b2Body* body2 = m_world->CreateBody(&bd2); - body1->CreateFixture(&fd1); - body2->CreateFixture(&fd2); + body1->CreateFixture(&fd1); + body2->CreateFixture(&fd2); - b2DistanceJointDef djd; + b2DistanceJointDef djd; - // Using a soft distance constraint can reduce some jitter. - // It also makes the structure seem a bit more fluid by - // acting like a suspension system. - djd.dampingRatio = 0.5f; - djd.frequencyHz = 10.0f; + // Using a soft distance constraint can reduce some jitter. + // It also makes the structure seem a bit more fluid by + // acting like a suspension system. + djd.dampingRatio = 0.5f; + djd.frequencyHz = 10.0f; - djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); - m_world->CreateJoint(&djd); + djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); + m_world->CreateJoint(&djd); - djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); - m_world->CreateJoint(&djd); + djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); + m_world->CreateJoint(&djd); - djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); - m_world->CreateJoint(&djd); + djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); + m_world->CreateJoint(&djd); - djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); - m_world->CreateJoint(&djd); + djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); + m_world->CreateJoint(&djd); - b2RevoluteJointDef rjd; + b2RevoluteJointDef rjd; - rjd.Initialize(body2, m_chassis, p4 + m_offset); - m_world->CreateJoint(&rjd); - } + rjd.Initialize(body2, m_chassis, p4 + m_offset); + m_world->CreateJoint(&rjd); + } - TheoJansen() - { - m_offset.Set(0.0f, 8.0f); - m_motorSpeed = 2.0f; - m_motorOn = true; - b2Vec2 pivot(0.0f, 0.8f); + TheoJansen() + { + m_offset.Set(0.0f, 8.0f); + m_motorSpeed = 2.0f; + m_motorOn = true; + b2Vec2 pivot(0.0f, 0.8f); - // Ground - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + // Ground + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; + shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); + shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); - shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); - ground->CreateFixture(&shape, 0.0f); - } + shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)); + ground->CreateFixture(&shape, 0.0f); + } - // Balls - for (int32 i = 0; i < 40; ++i) - { - b2CircleShape shape; - shape.m_radius = 0.25f; + // Balls + for (int32 i = 0; i < 40; ++i) + { + b2CircleShape shape; + shape.m_radius = 0.25f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-40.0f + 2.0f * i, 0.5f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-40.0f + 2.0f * i, 0.5f); - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 1.0f); - } + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 1.0f); + } - // Chassis - { - b2PolygonShape shape; - shape.SetAsBox(2.5f, 1.0f); + // Chassis + { + b2PolygonShape shape; + shape.SetAsBox(2.5f, 1.0f); - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_chassis = m_world->CreateBody(&bd); - m_chassis->CreateFixture(&sd); - } + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_chassis = m_world->CreateBody(&bd); + m_chassis->CreateFixture(&sd); + } - { - b2CircleShape shape; - shape.m_radius = 1.6f; + { + b2CircleShape shape; + shape.m_radius = 1.6f; - b2FixtureDef sd; - sd.density = 1.0f; - sd.shape = &shape; - sd.filter.groupIndex = -1; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = pivot + m_offset; - m_wheel = m_world->CreateBody(&bd); - m_wheel->CreateFixture(&sd); - } + b2FixtureDef sd; + sd.density = 1.0f; + sd.shape = &shape; + sd.filter.groupIndex = -1; + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = pivot + m_offset; + m_wheel = m_world->CreateBody(&bd); + m_wheel->CreateFixture(&sd); + } - { - b2RevoluteJointDef jd; - jd.Initialize(m_wheel, m_chassis, pivot + m_offset); - jd.collideConnected = false; - jd.motorSpeed = m_motorSpeed; - jd.maxMotorTorque = 400.0f; - jd.enableMotor = m_motorOn; - m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + { + b2RevoluteJointDef jd; + jd.Initialize(m_wheel, m_chassis, pivot + m_offset); + jd.collideConnected = false; + jd.motorSpeed = m_motorSpeed; + jd.maxMotorTorque = 400.0f; + jd.enableMotor = m_motorOn; + m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - b2Vec2 wheelAnchor; - - wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); + b2Vec2 wheelAnchor; + + wheelAnchor = pivot + b2Vec2(0.0f, -0.8f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); - m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); + m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); - m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); - CreateLeg(-1.0f, wheelAnchor); - CreateLeg(1.0f, wheelAnchor); - } + m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180.0f); + CreateLeg(-1.0f, wheelAnchor); + CreateLeg(1.0f, wheelAnchor); + } - void Step(Settings* settings) - { - m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); - m_textLine += 15; + void Step(Settings* settings) + { + m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); + m_textLine += DRAW_STRING_NEW_LINE; - Test::Step(settings); - } + Test::Step(settings); + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'a': - m_motorJoint->SetMotorSpeed(-m_motorSpeed); - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'a': + m_motorJoint->SetMotorSpeed(-m_motorSpeed); + break; - case 's': - m_motorJoint->SetMotorSpeed(0.0f); - break; + case 's': + m_motorJoint->SetMotorSpeed(0.0f); + break; - case 'd': - m_motorJoint->SetMotorSpeed(m_motorSpeed); - break; + case 'd': + m_motorJoint->SetMotorSpeed(m_motorSpeed); + break; - case 'm': - m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); - break; - } - } + case 'm': + m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); + break; + } + } - static Test* Create() - { - return new TheoJansen; - } + static Test* Create() + { + return new TheoJansen; + } - b2Vec2 m_offset; - b2Body* m_chassis; - b2Body* m_wheel; - b2RevoluteJoint* m_motorJoint; - bool m_motorOn; - float32 m_motorSpeed; + b2Vec2 m_offset; + b2Body* m_chassis; + b2Body* m_wheel; + b2RevoluteJoint* m_motorJoint; + bool m_motorOn; + float32 m_motorSpeed; }; #endif // THEO_JANSEN_H diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h index 90df463a72..9d675d2c88 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h @@ -24,133 +24,133 @@ class Tiles : public Test { public: - enum - { - e_count = 20 - }; + enum + { + e_count = 20 + }; - Tiles() - { - m_fixtureCount = 0; - b2Timer timer; + Tiles() + { + m_fixtureCount = 0; + b2Timer timer; - { - float32 a = 0.5f; - b2BodyDef bd; - bd.position.y = -a; - b2Body* ground = m_world->CreateBody(&bd); + { + float32 a = 0.5f; + b2BodyDef bd; + bd.position.y = -a; + b2Body* ground = m_world->CreateBody(&bd); #if 1 - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - ++m_fixtureCount; - position.x += 2.0f * a; - } - position.y -= 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + ++m_fixtureCount; + position.x += 2.0f * a; + } + position.y -= 2.0f * a; + } #else - int32 N = 200; - int32 M = 10; - b2Vec2 position; - position.x = -N * a; - for (int32 i = 0; i < N; ++i) - { - position.y = 0.0f; - for (int32 j = 0; j < M; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(a, a, position, 0.0f); - ground->CreateFixture(&shape, 0.0f); - position.y -= 2.0f * a; - } - position.x += 2.0f * a; - } + int32 N = 200; + int32 M = 10; + b2Vec2 position; + position.x = -N * a; + for (int32 i = 0; i < N; ++i) + { + position.y = 0.0f; + for (int32 j = 0; j < M; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(a, a, position, 0.0f); + ground->CreateFixture(&shape, 0.0f); + position.y -= 2.0f * a; + } + position.x += 2.0f * a; + } #endif - } + } - { - float32 a = 0.5f; - b2PolygonShape shape; - shape.SetAsBox(a, a); + { + float32 a = 0.5f; + b2PolygonShape shape; + shape.SetAsBox(a, a); - b2Vec2 x(-7.0f, 0.75f); - b2Vec2 y; - b2Vec2 deltaX(0.5625f, 1.25f); - b2Vec2 deltaY(1.125f, 0.0f); + b2Vec2 x(-7.0f, 0.75f); + b2Vec2 y; + b2Vec2 deltaX(0.5625f, 1.25f); + b2Vec2 deltaY(1.125f, 0.0f); - for (int32 i = 0; i < e_count; ++i) - { - y = x; + for (int32 i = 0; i < e_count; ++i) + { + y = x; - for (int32 j = i; j < e_count; ++j) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position = y; + for (int32 j = i; j < e_count; ++j) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position = y; - //if (i == 0 && j == 0) - //{ - // bd.allowSleep = false; - //} - //else - //{ - // bd.allowSleep = true; - //} + //if (i == 0 && j == 0) + //{ + // bd.allowSleep = false; + //} + //else + //{ + // bd.allowSleep = true; + //} - b2Body* body = m_world->CreateBody(&bd); - body->CreateFixture(&shape, 5.0f); - ++m_fixtureCount; - y += deltaY; - } + b2Body* body = m_world->CreateBody(&bd); + body->CreateFixture(&shape, 5.0f); + ++m_fixtureCount; + y += deltaY; + } - x += deltaX; - } - } + x += deltaX; + } + } - m_createTime = timer.GetMilliseconds(); - } + m_createTime = timer.GetMilliseconds(); + } - void Step(Settings* settings) - { - const b2ContactManager& cm = m_world->GetContactManager(); - int32 height = cm.m_broadPhase.GetTreeHeight(); - int32 leafCount = cm.m_broadPhase.GetProxyCount(); - int32 minimumNodeCount = 2 * leafCount - 1; - float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); - m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); - m_textLine += 15; + void Step(Settings* settings) + { + const b2ContactManager& cm = m_world->GetContactManager(); + int32 height = cm.m_broadPhase.GetTreeHeight(); + int32 leafCount = cm.m_broadPhase.GetProxyCount(); + int32 minimumNodeCount = 2 * leafCount - 1; + float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); + m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); + m_textLine += DRAW_STRING_NEW_LINE; - Test::Step(settings); + Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", - m_createTime, m_fixtureCount); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", + m_createTime, m_fixtureCount); + m_textLine += DRAW_STRING_NEW_LINE; - //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; + //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; - //if (m_stepCount == 400) - //{ - // tree->RebuildBottomUp(); - //} - } + //if (m_stepCount == 400) + //{ + // tree->RebuildBottomUp(); + //} + } - static Test* Create() - { - return new Tiles; - } + static Test* Create() + { + return new Tiles; + } - int32 m_fixtureCount; - float32 m_createTime; + int32 m_fixtureCount; + float32 m_createTime; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h index f3ad724d02..3d72eeda7b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h @@ -22,108 +22,106 @@ class TimeOfImpact : public Test { public: - TimeOfImpact() - { - m_shapeA.SetAsBox(25.0f, 5.0f); - m_shapeB.SetAsBox(2.5f, 2.5f); - } + TimeOfImpact() + { + m_shapeA.SetAsBox(25.0f, 5.0f); + m_shapeB.SetAsBox(2.5f, 2.5f); + } - static Test* Create() - { - return new TimeOfImpact; - } + static Test* Create() + { + return new TimeOfImpact; + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - b2Sweep sweepA; - sweepA.alpha0 = 0; - sweepA.c0.Set(24.0f, -60.0f); - sweepA.a0 = 2.95f; - sweepA.c = sweepA.c0; - sweepA.a = sweepA.a0; - sweepA.localCenter.SetZero(); + b2Sweep sweepA; + sweepA.c0.Set(24.0f, -60.0f); + sweepA.a0 = 2.95f; + sweepA.c = sweepA.c0; + sweepA.a = sweepA.a0; + sweepA.localCenter.SetZero(); - b2Sweep sweepB; - sweepB.alpha0 = 0; - sweepB.c0.Set(53.474274f, -50.252514f); - sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; - sweepB.c.Set(54.595478f, -51.083473f); - sweepB.a = 513.62781f; // - 162.0f * b2_pi; - sweepB.localCenter.SetZero(); + b2Sweep sweepB; + sweepB.c0.Set(53.474274f, -50.252514f); + sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; + sweepB.c.Set(54.595478f, -51.083473f); + sweepB.a = 513.62781f; // - 162.0f * b2_pi; + sweepB.localCenter.SetZero(); - //sweepB.a0 -= 300.0f * b2_pi; - //sweepB.a -= 300.0f * b2_pi; + //sweepB.a0 -= 300.0f * b2_pi; + //sweepB.a -= 300.0f * b2_pi; - b2TOIInput input; - input.proxyA.Set(&m_shapeA, 0); - input.proxyB.Set(&m_shapeB, 0); - input.sweepA = sweepA; - input.sweepB = sweepB; - input.tMax = 1.0f; + b2TOIInput input; + input.proxyA.Set(&m_shapeA, 0); + input.proxyB.Set(&m_shapeB, 0); + input.sweepA = sweepA; + input.sweepB = sweepB; + input.tMax = 1.0f; - b2TOIOutput output; + b2TOIOutput output; - b2TimeOfImpact(&output, &input); + b2TimeOfImpact(&output, &input); - m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t); - m_textLine += 15; + m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t); + m_textLine += DRAW_STRING_NEW_LINE; - extern int32 b2_toiMaxIters, b2_toiMaxRootIters; - m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); - m_textLine += 15; + extern int32 b2_toiMaxIters, b2_toiMaxRootIters; + m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, max root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); + m_textLine += DRAW_STRING_NEW_LINE; - b2Vec2 vertices[b2_maxPolygonVertices]; + b2Vec2 vertices[b2_maxPolygonVertices]; - b2Transform transformA; - sweepA.GetTransform(&transformA, 0.0f); - for (int32 i = 0; i < m_shapeA.m_vertexCount; ++i) - { - vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); - } - m_debugDraw.DrawPolygon(vertices, m_shapeA.m_vertexCount, b2Color(0.9f, 0.9f, 0.9f)); + b2Transform transformA; + sweepA.GetTransform(&transformA, 0.0f); + for (int32 i = 0; i < m_shapeA.m_count; ++i) + { + vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]); + } + m_debugDraw.DrawPolygon(vertices, m_shapeA.m_count, b2Color(0.9f, 0.9f, 0.9f)); - b2Transform transformB; - sweepB.GetTransform(&transformB, 0.0f); - - b2Vec2 localPoint(2.0f, -0.1f); + b2Transform transformB; + sweepB.GetTransform(&transformB, 0.0f); + + //b2Vec2 localPoint(2.0f, -0.1f); - for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.9f, 0.5f)); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.9f, 0.5f)); - sweepB.GetTransform(&transformB, output.t); - for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.5f, 0.7f, 0.9f)); + sweepB.GetTransform(&transformB, output.t); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.5f, 0.7f, 0.9f)); - sweepB.GetTransform(&transformB, 1.0f); - for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f)); + sweepB.GetTransform(&transformB, 1.0f); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); #if 0 - for (float32 t = 0.0f; t < 1.0f; t += 0.1f) - { - sweepB.GetTransform(&transformB, t); - for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) - { - vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); - } - m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0.9f, 0.5f, 0.5f)); - } + for (float32 t = 0.0f; t < 1.0f; t += 0.1f) + { + sweepB.GetTransform(&transformB, t); + for (int32 i = 0; i < m_shapeB.m_count; ++i) + { + vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]); + } + m_debugDraw.DrawPolygon(vertices, m_shapeB.m_count, b2Color(0.9f, 0.5f, 0.5f)); + } #endif - } + } - b2PolygonShape m_shapeA; - b2PolygonShape m_shapeB; + b2PolygonShape m_shapeA; + b2PolygonShape m_shapeB; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h index f8dbf37104..d2c6c62ee8 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h @@ -23,77 +23,77 @@ class Tumbler : public Test { public: - enum - { - e_count = 800 - }; + enum + { + e_count = 800 + }; - Tumbler() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); - } + Tumbler() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); + } - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.allowSleep = false; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.allowSleep = false; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); - shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); - body->CreateFixture(&shape, 5.0f); + b2PolygonShape shape; + shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); + shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0); + body->CreateFixture(&shape, 5.0f); - b2RevoluteJointDef jd; - jd.bodyA = ground; - jd.bodyB = body; - jd.localAnchorA.Set(0.0f, 10.0f); - jd.localAnchorB.Set(0.0f, 0.0f); - jd.referenceAngle = 0.0f; - jd.motorSpeed = 0.05f * b2_pi; - jd.maxMotorTorque = 1e8f; - jd.enableMotor = true; - m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); - } + b2RevoluteJointDef jd; + jd.bodyA = ground; + jd.bodyB = body; + jd.localAnchorA.Set(0.0f, 10.0f); + jd.localAnchorB.Set(0.0f, 0.0f); + jd.referenceAngle = 0.0f; + jd.motorSpeed = 0.05f * b2_pi; + jd.maxMotorTorque = 1e8f; + jd.enableMotor = true; + m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd); + } - m_count = 0; - } + m_count = 0; + } - void Step(Settings* settings) - { - Test::Step(settings); + void Step(Settings* settings) + { + Test::Step(settings); - if (m_count < e_count) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(0.0f, 10.0f); - b2Body* body = m_world->CreateBody(&bd); + if (m_count < e_count) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(0.0f, 10.0f); + b2Body* body = m_world->CreateBody(&bd); - b2PolygonShape shape; - shape.SetAsBox(0.125f, 0.125f); - body->CreateFixture(&shape, 1.0f); + b2PolygonShape shape; + shape.SetAsBox(0.125f, 0.125f); + body->CreateFixture(&shape, 1.0f); - ++m_count; - } - } + ++m_count; + } + } - static Test* Create() - { - return new Tumbler; - } + static Test* Create() + { + return new Tumbler; + } - b2RevoluteJoint* m_joint; - int32 m_count; + b2RevoluteJoint* m_joint; + int32 m_count; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h index 8079d5e6ca..c85a496b0b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h @@ -23,102 +23,102 @@ class VaryingFriction : public Test { public: - VaryingFriction() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + VaryingFriction() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2BodyDef bd; - bd.position.Set(-4.0f, 22.0f); - bd.angle = -0.25f; + b2BodyDef bd; + bd.position.Set(-4.0f, 22.0f); + bd.angle = -0.25f; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); - b2BodyDef bd; - bd.position.Set(10.5f, 19.0f); + b2BodyDef bd; + bd.position.Set(10.5f, 19.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2BodyDef bd; - bd.position.Set(4.0f, 14.0f); - bd.angle = 0.25f; + b2BodyDef bd; + bd.position.Set(4.0f, 14.0f); + bd.angle = 0.25f; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.25f, 1.0f); + { + b2PolygonShape shape; + shape.SetAsBox(0.25f, 1.0f); - b2BodyDef bd; - bd.position.Set(-10.5f, 11.0f); + b2BodyDef bd; + bd.position.Set(-10.5f, 11.0f); - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(13.0f, 0.25f); + { + b2PolygonShape shape; + shape.SetAsBox(13.0f, 0.25f); - b2BodyDef bd; - bd.position.Set(-4.0f, 6.0f); - bd.angle = -0.25f; + b2BodyDef bd; + bd.position.Set(-4.0f, 6.0f); + bd.angle = -0.25f; - b2Body* ground = m_world->CreateBody(&bd); - ground->CreateFixture(&shape, 0.0f); - } + b2Body* ground = m_world->CreateBody(&bd); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 25.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 25.0f; - float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; + float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}; - for (int i = 0; i < 5; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-15.0f + 4.0f * i, 28.0f); - b2Body* body = m_world->CreateBody(&bd); + for (int i = 0; i < 5; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-15.0f + 4.0f * i, 28.0f); + b2Body* body = m_world->CreateBody(&bd); - fd.friction = friction[i]; - body->CreateFixture(&fd); - } - } - } + fd.friction = friction[i]; + body->CreateFixture(&fd); + } + } + } - static Test* Create() - { - return new VaryingFriction; - } + static Test* Create() + { + return new VaryingFriction; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h index f86f916fa8..c06aca0a87 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h @@ -25,45 +25,45 @@ class VaryingRestitution : public Test { public: - VaryingRestitution() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + VaryingRestitution() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2CircleShape shape; - shape.m_radius = 1.0f; + { + b2CircleShape shape; + shape.m_radius = 1.0f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; - float32 restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; + float32 restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; - for (int32 i = 0; i < 7; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.position.Set(-10.0f + 3.0f * i, 20.0f); + for (int32 i = 0; i < 7; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.position.Set(-10.0f + 3.0f * i, 20.0f); - b2Body* body = m_world->CreateBody(&bd); + b2Body* body = m_world->CreateBody(&bd); - fd.restitution = restitution[i]; - body->CreateFixture(&fd); - } - } - } + fd.restitution = restitution[i]; + body->CreateFixture(&fd); + } + } + } - static Test* Create() - { - return new VaryingRestitution; - } + static Test* Create() + { + return new VaryingRestitution; + } }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h index 36090e53b3..a5c74f83ef 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h @@ -23,143 +23,143 @@ class VerticalStack : public Test { public: - enum - { - e_columnCount = 5, - e_rowCount = 16 - //e_columnCount = 1, - //e_rowCount = 1 - }; + enum + { + e_columnCount = 5, + e_rowCount = 16 + //e_columnCount = 1, + //e_rowCount = 1 + }; - VerticalStack() - { - { - b2BodyDef bd; - b2Body* ground = m_world->CreateBody(&bd); + VerticalStack() + { + { + b2BodyDef bd; + b2Body* ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); - shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); - ground->CreateFixture(&shape, 0.0f); - } + shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)); + ground->CreateFixture(&shape, 0.0f); + } - float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; + float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; - for (int32 j = 0; j < e_columnCount; ++j) - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + for (int32 j = 0; j < e_columnCount; ++j) + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 1.0f; - fd.friction = 0.3f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 1.0f; + fd.friction = 0.3f; - for (int i = 0; i < e_rowCount; ++i) - { - b2BodyDef bd; - bd.type = b2_dynamicBody; + for (int i = 0; i < e_rowCount; ++i) + { + b2BodyDef bd; + bd.type = b2_dynamicBody; - int32 n = j * e_rowCount + i; - b2Assert(n < e_rowCount * e_columnCount); - m_indices[n] = n; - bd.userData = m_indices + n; + int32 n = j * e_rowCount + i; + b2Assert(n < e_rowCount * e_columnCount); + m_indices[n] = n; + bd.userData = m_indices + n; - float32 x = 0.0f; - //float32 x = RandomFloat(-0.02f, 0.02f); - //float32 x = i % 2 == 0 ? -0.025f : 0.025f; - bd.position.Set(xs[j] + x, 0.752f + 1.54f * i); - b2Body* body = m_world->CreateBody(&bd); + float32 x = 0.0f; + //float32 x = RandomFloat(-0.02f, 0.02f); + //float32 x = i % 2 == 0 ? -0.025f : 0.025f; + bd.position.Set(xs[j] + x, 0.752f + 1.54f * i); + b2Body* body = m_world->CreateBody(&bd); - m_bodies[n] = body; + m_bodies[n] = body; - body->CreateFixture(&fd); - } - } + body->CreateFixture(&fd); + } + } - m_bullet = NULL; - } + m_bullet = NULL; + } - void Keyboard(unsigned char key) - { - switch (key) - { - case ',': - if (m_bullet != NULL) - { - m_world->DestroyBody(m_bullet); - m_bullet = NULL; - } + void Keyboard(unsigned char key) + { + switch (key) + { + case ',': + if (m_bullet != NULL) + { + m_world->DestroyBody(m_bullet); + m_bullet = NULL; + } - { - b2CircleShape shape; - shape.m_radius = 0.25f; + { + b2CircleShape shape; + shape.m_radius = 0.25f; - b2FixtureDef fd; - fd.shape = &shape; - fd.density = 20.0f; - fd.restitution = 0.05f; + b2FixtureDef fd; + fd.shape = &shape; + fd.density = 20.0f; + fd.restitution = 0.05f; - b2BodyDef bd; - bd.type = b2_dynamicBody; - bd.bullet = true; - bd.position.Set(-31.0f, 5.0f); + b2BodyDef bd; + bd.type = b2_dynamicBody; + bd.bullet = true; + bd.position.Set(-31.0f, 5.0f); - m_bullet = m_world->CreateBody(&bd); - m_bullet->CreateFixture(&fd); + m_bullet = m_world->CreateBody(&bd); + m_bullet->CreateFixture(&fd); - m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - } - break; - } - } + m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + } + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bullet."); - m_textLine += 15; + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bullet."); + m_textLine += DRAW_STRING_NEW_LINE; - //if (m_stepCount == 300) - //{ - // if (m_bullet != NULL) - // { - // m_world->DestroyBody(m_bullet); - // m_bullet = NULL; - // } + //if (m_stepCount == 300) + //{ + // if (m_bullet != NULL) + // { + // m_world->DestroyBody(m_bullet); + // m_bullet = NULL; + // } - // { - // b2CircleShape shape; - // shape.m_radius = 0.25f; + // { + // b2CircleShape shape; + // shape.m_radius = 0.25f; - // b2FixtureDef fd; - // fd.shape = &shape; - // fd.density = 20.0f; - // fd.restitution = 0.05f; + // b2FixtureDef fd; + // fd.shape = &shape; + // fd.density = 20.0f; + // fd.restitution = 0.05f; - // b2BodyDef bd; - // bd.type = b2_dynamicBody; - // bd.bullet = true; - // bd.position.Set(-31.0f, 5.0f); + // b2BodyDef bd; + // bd.type = b2_dynamicBody; + // bd.bullet = true; + // bd.position.Set(-31.0f, 5.0f); - // m_bullet = m_world->CreateBody(&bd); - // m_bullet->CreateFixture(&fd); + // m_bullet = m_world->CreateBody(&bd); + // m_bullet->CreateFixture(&fd); - // m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); - // } - //} - } + // m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f)); + // } + //} + } - static Test* Create() - { - return new VerticalStack; - } + static Test* Create() + { + return new VerticalStack; + } - b2Body* m_bullet; - b2Body* m_bodies[e_rowCount * e_columnCount]; - int32 m_indices[e_rowCount * e_columnCount]; + b2Body* m_bullet; + b2Body* m_bodies[e_rowCount * e_columnCount]; + int32 m_indices[e_rowCount * e_columnCount]; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h index 72fdbcdf14..cf255bd666 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h @@ -23,187 +23,187 @@ class Web : public Test { public: - Web() - { - b2Body* ground = NULL; - { - b2BodyDef bd; - ground = m_world->CreateBody(&bd); + Web() + { + b2Body* ground = NULL; + { + b2BodyDef bd; + ground = m_world->CreateBody(&bd); - b2EdgeShape shape; - shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); - ground->CreateFixture(&shape, 0.0f); - } + b2EdgeShape shape; + shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); + ground->CreateFixture(&shape, 0.0f); + } - { - b2PolygonShape shape; - shape.SetAsBox(0.5f, 0.5f); + { + b2PolygonShape shape; + shape.SetAsBox(0.5f, 0.5f); - b2BodyDef bd; - bd.type = b2_dynamicBody; + b2BodyDef bd; + bd.type = b2_dynamicBody; - bd.position.Set(-5.0f, 5.0f); - m_bodies[0] = m_world->CreateBody(&bd); - m_bodies[0]->CreateFixture(&shape, 5.0f); + bd.position.Set(-5.0f, 5.0f); + m_bodies[0] = m_world->CreateBody(&bd); + m_bodies[0]->CreateFixture(&shape, 5.0f); - bd.position.Set(5.0f, 5.0f); - m_bodies[1] = m_world->CreateBody(&bd); - m_bodies[1]->CreateFixture(&shape, 5.0f); + bd.position.Set(5.0f, 5.0f); + m_bodies[1] = m_world->CreateBody(&bd); + m_bodies[1]->CreateFixture(&shape, 5.0f); - bd.position.Set(5.0f, 15.0f); - m_bodies[2] = m_world->CreateBody(&bd); - m_bodies[2]->CreateFixture(&shape, 5.0f); + bd.position.Set(5.0f, 15.0f); + m_bodies[2] = m_world->CreateBody(&bd); + m_bodies[2]->CreateFixture(&shape, 5.0f); - bd.position.Set(-5.0f, 15.0f); - m_bodies[3] = m_world->CreateBody(&bd); - m_bodies[3]->CreateFixture(&shape, 5.0f); + bd.position.Set(-5.0f, 15.0f); + m_bodies[3] = m_world->CreateBody(&bd); + m_bodies[3]->CreateFixture(&shape, 5.0f); - b2DistanceJointDef jd; - b2Vec2 p1, p2, d; + b2DistanceJointDef jd; + b2Vec2 p1, p2, d; - jd.frequencyHz = 2.0f; - jd.dampingRatio = 0.0f; + jd.frequencyHz = 2.0f; + jd.dampingRatio = 0.0f; - jd.bodyA = ground; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(-10.0f, 0.0f); - jd.localAnchorB.Set(-0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[0] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(-10.0f, 0.0f); + jd.localAnchorB.Set(-0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[0] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(10.0f, 0.0f); - jd.localAnchorB.Set(0.5f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[1] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(10.0f, 0.0f); + jd.localAnchorB.Set(0.5f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[1] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(10.0f, 20.0f); - jd.localAnchorB.Set(0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[2] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(10.0f, 20.0f); + jd.localAnchorB.Set(0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[2] = m_world->CreateJoint(&jd); - jd.bodyA = ground; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-10.0f, 20.0f); - jd.localAnchorB.Set(-0.5f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[3] = m_world->CreateJoint(&jd); + jd.bodyA = ground; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-10.0f, 20.0f); + jd.localAnchorB.Set(-0.5f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[3] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[0]; - jd.bodyB = m_bodies[1]; - jd.localAnchorA.Set(0.5f, 0.0f); - jd.localAnchorB.Set(-0.5f, 0.0f);; - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[4] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[0]; + jd.bodyB = m_bodies[1]; + jd.localAnchorA.Set(0.5f, 0.0f); + jd.localAnchorB.Set(-0.5f, 0.0f);; + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[4] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[1]; - jd.bodyB = m_bodies[2]; - jd.localAnchorA.Set(0.0f, 0.5f); - jd.localAnchorB.Set(0.0f, -0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[5] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[1]; + jd.bodyB = m_bodies[2]; + jd.localAnchorA.Set(0.0f, 0.5f); + jd.localAnchorB.Set(0.0f, -0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[5] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[2]; - jd.bodyB = m_bodies[3]; - jd.localAnchorA.Set(-0.5f, 0.0f); - jd.localAnchorB.Set(0.5f, 0.0f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[6] = m_world->CreateJoint(&jd); + jd.bodyA = m_bodies[2]; + jd.bodyB = m_bodies[3]; + jd.localAnchorA.Set(-0.5f, 0.0f); + jd.localAnchorB.Set(0.5f, 0.0f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[6] = m_world->CreateJoint(&jd); - jd.bodyA = m_bodies[3]; - jd.bodyB = m_bodies[0]; - jd.localAnchorA.Set(0.0f, -0.5f); - jd.localAnchorB.Set(0.0f, 0.5f); - p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); - p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); - d = p2 - p1; - jd.length = d.Length(); - m_joints[7] = m_world->CreateJoint(&jd); - } - } + jd.bodyA = m_bodies[3]; + jd.bodyB = m_bodies[0]; + jd.localAnchorA.Set(0.0f, -0.5f); + jd.localAnchorB.Set(0.0f, 0.5f); + p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); + p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); + d = p2 - p1; + jd.length = d.Length(); + m_joints[7] = m_world->CreateJoint(&jd); + } + } - void Keyboard(unsigned char key) - { - switch (key) - { - case 'b': - for (int32 i = 0; i < 4; ++i) - { - if (m_bodies[i]) - { - m_world->DestroyBody(m_bodies[i]); - m_bodies[i] = NULL; - break; - } - } - break; + void Keyboard(unsigned char key) + { + switch (key) + { + case 'b': + for (int32 i = 0; i < 4; ++i) + { + if (m_bodies[i]) + { + m_world->DestroyBody(m_bodies[i]); + m_bodies[i] = NULL; + break; + } + } + break; - case 'j': - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i]) - { - m_world->DestroyJoint(m_joints[i]); - m_joints[i] = NULL; - break; - } - } - break; - } - } + case 'j': + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i]) + { + m_world->DestroyJoint(m_joints[i]); + m_joints[i] = NULL; + break; + } + } + break; + } + } - void Step(Settings* settings) - { - Test::Step(settings); - m_debugDraw.DrawString(5, m_textLine, "This demonstrates a soft distance joint."); - m_textLine += 15; - m_debugDraw.DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); - m_textLine += 15; - } + void Step(Settings* settings) + { + Test::Step(settings); + m_debugDraw.DrawString(5, m_textLine, "This demonstrates a soft distance joint."); + m_textLine += DRAW_STRING_NEW_LINE; + m_debugDraw.DrawString(5, m_textLine, "Press: (b) to delete a body, (j) to delete a joint"); + m_textLine += DRAW_STRING_NEW_LINE; + } - void JointDestroyed(b2Joint* joint) - { - for (int32 i = 0; i < 8; ++i) - { - if (m_joints[i] == joint) - { - m_joints[i] = NULL; - break; - } - } - } + void JointDestroyed(b2Joint* joint) + { + for (int32 i = 0; i < 8; ++i) + { + if (m_joints[i] == joint) + { + m_joints[i] = NULL; + break; + } + } + } - static Test* Create() - { - return new Web; - } + static Test* Create() + { + return new Web; + } - b2Body* m_bodies[4]; - b2Joint* m_joints[8]; + b2Body* m_bodies[4]; + b2Joint* m_joints[8]; }; #endif From 8574fb0494bda54415b4365e15be301bed5e9ff8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 25 Nov 2013 15:11:43 +0800 Subject: [PATCH 29/75] Build fix for XMLHttpRequest after using std::unordered_map instead of std::map. --- cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index cb33e9d413..e3524aba36 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -114,7 +114,7 @@ void MinXmlHttpRequest::_setRequestHeader(const char* field, const char* value) stringstream value_s; string header; - map::iterator iter = _requestHeader.find(field); + auto iter = _requestHeader.find(field); // Concatenate values when header exists. if (iter != _requestHeader.end()) From b9fa8566f2e4f08fa80caf74686e227c268f7882 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 25 Nov 2013 15:52:59 +0800 Subject: [PATCH 30/75] closed #3273: ScriptingCore::evalString crashes --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 0f7fca11f4..8351066959 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -397,11 +397,15 @@ JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char * cx = _cx; if (global == NULL) global = _global; + + JSAutoCompartment ac(cx, global); + JSScript* script = JS_CompileScript(cx, global, string, strlen(string), filename, 1); - if (script) { - JSAutoCompartment ac(cx, global); + if (script) + { JSBool evaluatedOK = JS_ExecuteScript(cx, global, script, outVal); - if (JS_FALSE == evaluatedOK) { + if (JS_FALSE == evaluatedOK) + { fprintf(stderr, "(evaluatedOK == JS_FALSE)\n"); } return evaluatedOK; From 805312b3d3958d8cf332bb9d6f8139ca83e90775 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 25 Nov 2013 15:55:01 +0800 Subject: [PATCH 31/75] fix box2d compile error in ndk --- external/Box2D/Collision/Shapes/b2ChainShape.cpp | 1 + external/Box2D/Collision/b2DynamicTree.cpp | 1 + external/Box2D/Common/b2BlockAllocator.cpp | 1 + external/Box2D/Common/b2GrowableStack.h | 1 + 4 files changed, 4 insertions(+) diff --git a/external/Box2D/Collision/Shapes/b2ChainShape.cpp b/external/Box2D/Collision/Shapes/b2ChainShape.cpp index 069b4cae84..010b9edcb9 100644 --- a/external/Box2D/Collision/Shapes/b2ChainShape.cpp +++ b/external/Box2D/Collision/Shapes/b2ChainShape.cpp @@ -20,6 +20,7 @@ #include #include #include +#include b2ChainShape::~b2ChainShape() { diff --git a/external/Box2D/Collision/b2DynamicTree.cpp b/external/Box2D/Collision/b2DynamicTree.cpp index 7035ab8b84..2607c6beee 100644 --- a/external/Box2D/Collision/b2DynamicTree.cpp +++ b/external/Box2D/Collision/b2DynamicTree.cpp @@ -18,6 +18,7 @@ #include #include +#include b2DynamicTree::b2DynamicTree() { diff --git a/external/Box2D/Common/b2BlockAllocator.cpp b/external/Box2D/Common/b2BlockAllocator.cpp index f7a4688ea9..b09a968435 100644 --- a/external/Box2D/Common/b2BlockAllocator.cpp +++ b/external/Box2D/Common/b2BlockAllocator.cpp @@ -20,6 +20,7 @@ #include #include #include +#include int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = { diff --git a/external/Box2D/Common/b2GrowableStack.h b/external/Box2D/Common/b2GrowableStack.h index 4094644a28..44813e3eab 100644 --- a/external/Box2D/Common/b2GrowableStack.h +++ b/external/Box2D/Common/b2GrowableStack.h @@ -20,6 +20,7 @@ #define B2_GROWABLE_STACK_H #include #include +#include /// This is a growable LIFO stack with an initial capacity of N. /// If the stack size exceeds the initial capacity, the heap is used From 09ba28d52279e6498c9ed725906a5ba54401f1ef Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 25 Nov 2013 17:57:06 +0800 Subject: [PATCH 32/75] issue #2771: refactor PhysicsWorld and PhysicsWorldInfo --- cocos/physics/CCPhysicsWorld.cpp | 597 +++++++++--------- .../box2d/CCPhysicsWorldInfo_box2d.cpp | 22 + .../physics/box2d/CCPhysicsWorldInfo_box2d.h | 11 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 61 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 13 +- 5 files changed, 380 insertions(+), 324 deletions(-) diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 59d7db9ae9..a8ca7a8d23 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -201,257 +201,6 @@ void PhysicsWorldCallback::queryPointFunc(cpShape *shape, cpFloat distance, cpVe PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } -void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) -{ - auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); - if (it != _delayRemoveJoints.end()) - { - _delayRemoveJoints.erase(it); - return; - } - - if (_info->getSpace()->locked_private) - { - if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) - { - _delayAddJoints.push_back(joint); - _delayDirty = true; - } - }else - { - doAddJoint(joint); - } -} - -void PhysicsWorld::removeJointOrDelay(PhysicsJoint* joint) -{ - auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); - if (it != _delayAddJoints.end()) - { - _delayAddJoints.erase(it); - return; - } - - if (_info->getSpace()->locked_private) - { - if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) - { - _delayRemoveJoints.push_back(joint); - _delayDirty = true; - } - }else - { - doRemoveJoint(joint); - } -} - -void PhysicsWorld::addJoint(PhysicsJoint* joint) -{ - if (joint->getWorld() != nullptr && joint->getWorld() != this) - { - joint->removeFormWorld(); - } - - addJointOrDelay(joint); - _joints.push_back(joint); - joint->_world = this; -} - -void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) -{ - if (joint->getWorld() != this) - { - if (destroy) - { - CCLOG("physics warnning: the joint is not in this world, it won't be destoried utill the body it conntect is destoried"); - } - return; - } - - removeJointOrDelay(joint); - - _joints.remove(joint); - joint->_world = nullptr; - - // clean the connection to this joint - if (destroy) - { - if (joint->getBodyA() != nullptr) - { - joint->getBodyA()->removeJoint(joint); - } - - if (joint->getBodyB() != nullptr) - { - joint->getBodyB()->removeJoint(joint); - } - - // test the distraction is delaied or not - if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) - { - joint->_destoryMark = true; - } - else - { - delete joint; - } - } -} - -void PhysicsWorld::removeAllJoints(bool destroy) -{ - for (auto joint : _joints) - { - removeJointOrDelay(joint); - joint->_world = nullptr; - - // clean the connection to this joint - if (destroy) - { - if (joint->getBodyA() != nullptr) - { - joint->getBodyA()->removeJoint(joint); - } - - if (joint->getBodyB() != nullptr) - { - joint->getBodyB()->removeJoint(joint); - } - - // test the distraction is delaied or not - if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) - { - joint->_destoryMark = true; - } - else - { - delete joint; - } - } - } - - _joints.clear(); -} - -void PhysicsWorld::addShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->getShapes()) - { - _info->addShape(cps); - } - - return; -} - -void PhysicsWorld::doAddJoint(PhysicsJoint *joint) -{ - for (auto subjoint : joint->_info->getJoints()) - { - _info->addJoint(subjoint); - } -} - -void PhysicsWorld::doRemoveBody(PhysicsBody* body) -{ - CCASSERT(body != nullptr, "the body can not be nullptr"); - - // reset the gravity - if (!body->isGravityEnabled()) - { - body->applyForce(-_gravity); - } - - // remove shaps - for (auto shape : *body->getShapes()) - { - removeShape(dynamic_cast(shape)); - } - - // remove body - _info->removeBody(*body->_info); -} - -void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) -{ - for (auto subjoint : joint->_info->getJoints()) - { - _info->removeJoint(subjoint); - } -} - -void PhysicsWorld::removeAllBodies() -{ - for (Object* obj : *_bodies) - { - PhysicsBody* child = dynamic_cast(obj); - removeBodyOrDelay(child); - child->_world = nullptr; - } - - _bodies->removeAllObjects(); - CC_SAFE_RELEASE(_bodies); -} - -void PhysicsWorld::removeShape(PhysicsShape* shape) -{ - for (auto cps : shape->_info->getShapes()) - { - if (cpSpaceContainsShape(_info->getSpace(), cps)) - { - cpSpaceRemoveShape(_info->getSpace(), cps); - } - } -} - -void PhysicsWorld::updateJoints() -{ - if (_info->getSpace()->locked_private) - { - return; - } - - for (auto joint : _delayAddJoints) - { - doAddJoint(joint); - } - - for (auto joint : _delayRemoveJoints) - { - doRemoveJoint(joint); - - if (joint->_destoryMark) - { - delete joint; - } - } - - _delayAddJoints.clear(); - _delayRemoveJoints.clear(); -} - -void PhysicsWorld::update(float delta) -{ - if (_delayDirty) - { - // the updateJoints must run before the updateBodies. - updateJoints(); - updateBodies(); - _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); - } - - for (auto body : *_bodies) - { - body->update(delta); - } - - cpSpaceStep(_info->getSpace(), delta); - - if (_debugDrawMask != DEBUGDRAW_NONE) - { - debugDraw(); - } -} - void PhysicsWorld::debugDraw() { if (_debugDraw == nullptr) @@ -489,16 +238,6 @@ void PhysicsWorld::debugDraw() } } -void PhysicsWorld::setDebugDrawMask(int mask) -{ - if (mask == DEBUGDRAW_NONE) - { - CC_SAFE_DELETE(_debugDraw); - } - - _debugDrawMask = mask; -} - int PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; @@ -603,28 +342,6 @@ void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact) _scene->getEventDispatcher()->dispatchEvent(&event); } -void PhysicsWorld::setGravity(const Vect& gravity) -{ - if (_bodies != nullptr) - { - for (auto child : *_bodies) - { - PhysicsBody* body = dynamic_cast(child); - - // reset gravity for body - if (!body->isGravityEnabled()) - { - body->applyForce(-_gravity); - body->applyForce(gravity); - } - } - } - - _gravity = gravity; - cpSpaceSetGravity(_info->getSpace(), PhysicsHelper::point2cpv(gravity)); -} - - void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data) { CCASSERT(func != nullptr, "func shouldn't be nullptr"); @@ -708,26 +425,6 @@ PhysicsShape* PhysicsWorld::getShape(const Point& point) const return shape == nullptr ? nullptr : PhysicsShapeInfo::getMap().find(shape)->second->getShape(); } -Array* PhysicsWorld::getAllBodies() const -{ - return _bodies; -} - -PhysicsBody* PhysicsWorld::getBody(int tag) const -{ - for (auto body : *_bodies) - { - if (((PhysicsBody*)body)->getTag() == tag) - { - return (PhysicsBody*)body; - } - } - - return nullptr; -} - - - void PhysicsDebugDraw::drawShape(PhysicsShape& shape) { for (auto it = shape._info->getShapes().begin(); it != shape._info->getShapes().end(); ++it) @@ -1052,6 +749,300 @@ void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) } } +void PhysicsWorld::doAddJoint(PhysicsJoint *joint) +{ + if (joint == nullptr || joint->_info == nullptr) + { + return; + } + + _info->addJoint(*joint->_info); +} + +void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy) +{ + if (joint->getWorld() != this) + { + if (destroy) + { + CCLOG("physics warnning: the joint is not in this world, it won't be destoried utill the body it conntect is destoried"); + } + return; + } + + removeJointOrDelay(joint); + + _joints.remove(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } +} + +void PhysicsWorld::updateJoints() +{ + if (_info->isLocked()) + { + return; + } + + for (auto joint : _delayAddJoints) + { + doAddJoint(joint); + } + + for (auto joint : _delayRemoveJoints) + { + doRemoveJoint(joint); + + if (joint->_destoryMark) + { + delete joint; + } + } + + _delayAddJoints.clear(); + _delayRemoveJoints.clear(); +} + +void PhysicsWorld::removeShape(PhysicsShape* shape) +{ + if (shape != nullptr) + { + _info->removeShape(*shape->_info); + } +} + +void PhysicsWorld::addJointOrDelay(PhysicsJoint* joint) +{ + auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint); + if (it != _delayRemoveJoints.end()) + { + _delayRemoveJoints.erase(it); + return; + } + + if (_info->isLocked()) + { + if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end()) + { + _delayAddJoints.push_back(joint); + _delayDirty = true; + } + }else + { + doAddJoint(joint); + } +} + +void PhysicsWorld::removeJointOrDelay(PhysicsJoint* joint) +{ + auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint); + if (it != _delayAddJoints.end()) + { + _delayAddJoints.erase(it); + return; + } + + if (_info->isLocked()) + { + if (std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint) == _delayRemoveJoints.end()) + { + _delayRemoveJoints.push_back(joint); + _delayDirty = true; + } + }else + { + doRemoveJoint(joint); + } +} + +void PhysicsWorld::addJoint(PhysicsJoint* joint) +{ + if (joint->getWorld() != nullptr && joint->getWorld() != this) + { + joint->removeFormWorld(); + } + + addJointOrDelay(joint); + _joints.push_back(joint); + joint->_world = this; +} + +void PhysicsWorld::removeAllJoints(bool destroy) +{ + for (auto joint : _joints) + { + removeJointOrDelay(joint); + joint->_world = nullptr; + + // clean the connection to this joint + if (destroy) + { + if (joint->getBodyA() != nullptr) + { + joint->getBodyA()->removeJoint(joint); + } + + if (joint->getBodyB() != nullptr) + { + joint->getBodyB()->removeJoint(joint); + } + + // test the distraction is delaied or not + if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) + { + joint->_destoryMark = true; + } + else + { + delete joint; + } + } + } + + _joints.clear(); +} + +void PhysicsWorld::addShape(PhysicsShape* shape) +{ + if (shape != nullptr) + { + _info->addShape(*shape->_info); + } +} + +void PhysicsWorld::doRemoveBody(PhysicsBody* body) +{ + CCASSERT(body != nullptr, "the body can not be nullptr"); + + // reset the gravity + if (!body->isGravityEnabled()) + { + body->applyForce(-_gravity); + } + + // remove shaps + for (auto shape : *body->getShapes()) + { + removeShape(dynamic_cast(shape)); + } + + // remove body + _info->removeBody(*body->_info); +} + +void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) +{ + _info->removeJoint(*joint->_info); +} + +void PhysicsWorld::removeAllBodies() +{ + for (Object* obj : *_bodies) + { + PhysicsBody* child = dynamic_cast(obj); + removeBodyOrDelay(child); + child->_world = nullptr; + } + + _bodies->removeAllObjects(); + CC_SAFE_RELEASE(_bodies); +} + +void PhysicsWorld::setDebugDrawMask(int mask) +{ + if (mask == DEBUGDRAW_NONE) + { + CC_SAFE_DELETE(_debugDraw); + } + + _debugDrawMask = mask; +} + +Array* PhysicsWorld::getAllBodies() const +{ + return _bodies; +} + +PhysicsBody* PhysicsWorld::getBody(int tag) const +{ + for (auto body : *_bodies) + { + if (((PhysicsBody*)body)->getTag() == tag) + { + return (PhysicsBody*)body; + } + } + + return nullptr; +} + +void PhysicsWorld::setGravity(const Vect& gravity) +{ + if (_bodies != nullptr) + { + for (auto child : *_bodies) + { + PhysicsBody* body = dynamic_cast(child); + + // reset gravity for body + if (!body->isGravityEnabled()) + { + body->applyForce(-_gravity); + body->applyForce(gravity); + } + } + } + + _gravity = gravity; + _info->setGravity(gravity); +} + +void PhysicsWorld::update(float delta) +{ + if (_delayDirty) + { + // the updateJoints must run before the updateBodies. + updateJoints(); + updateBodies(); + _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + } + + for (auto body : *_bodies) + { + body->update(delta); + } + + _info->step(delta); + + if (_debugDrawMask != DEBUGDRAW_NONE) + { + debugDraw(); + } +} + PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp index 22235293b9..2215a27692 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp @@ -27,6 +27,8 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) #include "CCPhysicsHelper_box2d.h" #include "CCPhysicsBodyInfo_box2d.h" +#include "CCPhysicsShapeInfo_box2d.h" +#include "CCPhysicsJointInfo_box2d.h" NS_CC_BEGIN PhysicsWorldInfo::PhysicsWorldInfo() @@ -63,5 +65,25 @@ void PhysicsWorldInfo::removeBody(PhysicsBodyInfo& body) } } +void PhysicsWorldInfo::addShape(PhysicsShapeInfo& shape) +{ + +} + +void PhysicsWorldInfo::removeShape(PhysicsShapeInfo& shape) +{ + +} + +void PhysicsWorldInfo::addJoint(PhysicsJointInfo& joint) +{ + +} + +void PhysicsWorldInfo::removeJoint(PhysicsJointInfo& joint) +{ + +} + NS_CC_END #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h index dbbfa5c0ab..faf7da0132 100644 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h +++ b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h @@ -31,18 +31,27 @@ #include "CCPlatformMacros.h" NS_CC_BEGIN class PhysicsBodyInfo; +class PhysicsJointInfo; +class PhysicsShapeInfo; class PhysicsWorldInfo { public: - void setGravity(const Vect& gravity); inline b2World* getWorld() { return _world; } + void addShape(PhysicsShapeInfo& shape); + void removeShape(PhysicsShapeInfo& shape); void addBody(PhysicsBodyInfo& body); void removeBody(PhysicsBodyInfo& body); + void addJoint(PhysicsJointInfo& joint); + void removeJoint(PhysicsJointInfo& joint); + void setGravity(const Vect& gravity); inline bool isLocked() { return _world->IsLocked(); } + inline void step(float delta) { _world->Step(delta, VELOCITY_ITERRATIONS, POSITION_ITERRATIONS); } private: b2World* _world; + static const int32 VELOCITY_ITERRATIONS = 8; + static const int32 POSITION_ITERRATIONS = 1; private: PhysicsWorldInfo(); diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index dbff438cb7..2f9ba4db18 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -26,22 +26,10 @@ #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "CCPhysicsHelper_chipmunk.h" #include "CCPhysicsBodyInfo_chipmunk.h" +#include "CCPhysicsShapeInfo_chipmunk.h" +#include "CCPhysicsJointInfo_chipmunk.h" NS_CC_BEGIN -#define PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(name, type) \ -void PhysicsWorldInfo::add##name(cp##type* data) \ -{ \ - if (!cpSpaceContains##type(_space, data)) cpSpaceAdd##type(_space, data); \ -} \ -\ -void PhysicsWorldInfo::remove##name(cp##type* data) \ -{ \ - if (cpSpaceContains##type(_space, data)) cpSpaceRemove##type(_space, data); \ -} \ - -PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Shape, Shape) -PHYSICS_WORLD_INFO_FUNCTION_IMPLEMENTS(Joint, Constraint) - PhysicsWorldInfo::PhysicsWorldInfo() { _space = cpSpaceNew(); @@ -59,11 +47,54 @@ void PhysicsWorldInfo::setGravity(const Vect& gravity) void PhysicsWorldInfo::addBody(PhysicsBodyInfo& body) { - if (cpSpaceContainsBody(_space, body.getBody())) + if (!cpSpaceContainsBody(_space, body.getBody())) { cpSpaceAddBody(_space, body.getBody()); } } +void PhysicsWorldInfo::removeBody(PhysicsBodyInfo& body) +{ + if (cpSpaceContainsBody(_space, body.getBody())) + { + cpSpaceRemoveBody(_space, body.getBody()); + } +} + +void PhysicsWorldInfo::addShape(PhysicsShapeInfo& shape) +{ + for (auto cps : shape.getShapes()) + { + cpSpaceAddShape(_space, cps); + } +} + +void PhysicsWorldInfo::removeShape(PhysicsShapeInfo& shape) +{ + for (auto cps : shape.getShapes()) + { + if (cpSpaceContainsShape(_space, cps)) + { + cpSpaceRemoveShape(_space, cps); + } + } +} + +void PhysicsWorldInfo::addJoint(PhysicsJointInfo& joint) +{ + for (auto subjoint : joint.getJoints()) + { + cpSpaceAddConstraint(_space, subjoint); + } +} + +void PhysicsWorldInfo::removeJoint(PhysicsJointInfo& joint) +{ + for (auto subjoint : joint.getJoints()) + { + cpSpaceRemoveConstraint(_space, subjoint); + } +} + NS_CC_END #endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 3b0a2f0eed..3e4ce9a965 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -34,19 +34,22 @@ #include "CCGeometry.h" NS_CC_BEGIN class PhysicsBodyInfo; +class PhysicsJointInfo; +class PhysicsShapeInfo; class PhysicsWorldInfo { public: - cpSpace* getWorld() const { return _space; } - void addShape(cpShape* shape); - void removeShape(cpShape* shape); + cpSpace* getSpace() const { return _space; } + void addShape(PhysicsShapeInfo& shape); + void removeShape(PhysicsShapeInfo& shape); void addBody(PhysicsBodyInfo& body); void removeBody(PhysicsBodyInfo& body); - void addJoint(cpConstraint* joint); - void removeJoint(cpConstraint* joint); + void addJoint(PhysicsJointInfo& joint); + void removeJoint(PhysicsJointInfo& joint); void setGravity(const Vect& gravity); inline bool isLocked() { return static_cast(_space->locked_private); } + inline void step(float delta) { cpSpaceStep(_space, delta); } private: PhysicsWorldInfo(); From 4538be2b434c6cea0b0f753c3319a3254f64496b Mon Sep 17 00:00:00 2001 From: Lajos Kamocsay Date: Mon, 25 Nov 2013 10:00:53 -0500 Subject: [PATCH 33/75] FontTest was not rendering TTFs --- samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp b/samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp index 8359a33418..ace7c1b569 100644 --- a/samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp +++ b/samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp @@ -16,7 +16,7 @@ static int fontIdx = 0; static std::string fontList[] = { -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) +#if ((CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)) // custom ttf files are defined in Test-info.plist "American Typewriter", "Marker Felt", From a198fb51df9ed79781a3f3c5b5ec89ad49130b10 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 25 Nov 2013 16:24:33 -0800 Subject: [PATCH 34/75] JS Bindings Menu doesn't initialize the menu twice. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 8ac72cc7c1..f72dd9cbdf 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -3194d28204e71875735934ee3207961ec14e655a \ No newline at end of file +e25d022404007994fb9abd210bd35646a217e49e \ No newline at end of file From 9f6d2db8ed1a4a90e1b99a47c9d68d590f7105ca Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 09:56:14 +0800 Subject: [PATCH 35/75] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 576904e3bf..dfa56dbe1e 100644 --- a/AUTHORS +++ b/AUTHORS @@ -659,6 +659,9 @@ Developers: bopohaa Fixed a bug that Webp test crashes. + lajos + FontTest isn't rendered correctly with custom TTF font on Mac platform. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From 5fbf16414243072e8a90174e04ec381a61120c52 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 10:14:56 +0800 Subject: [PATCH 36/75] closed #3274: Can't override cc.Node.setPosition in JSB. --- ...bindings_chipmunk_functions_registration.h | 546 +++++++++--------- .../js_bindings_chipmunk_registration.cpp | 20 +- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../cocostudio/jsb_cocos2dx_studio_manual.cpp | 6 +- .../jsb_cocos2dx_extension_manual.cpp | 12 +- .../bindings/gui/jsb_cocos2dx_gui_manual.cpp | 16 +- 6 files changed, 301 insertions(+), 301 deletions(-) diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h index 20e87592f9..835575c3d0 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions_registration.h @@ -7,279 +7,279 @@ #ifdef JSB_INCLUDE_CHIPMUNK #include "js_bindings_chipmunk_manual.h" -JS_DefineFunction(cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); -JS_DefineFunction(cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetCount", JSB_cpArbiterGetCount, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetDepth", JSB_cpArbiterGetDepth, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetElasticity", JSB_cpArbiterGetElasticity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetFriction", JSB_cpArbiterGetFriction, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetNormal", JSB_cpArbiterGetNormal, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetPoint", JSB_cpArbiterGetPoint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterGetSurfaceVelocity", JSB_cpArbiterGetSurfaceVelocity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterIgnore", JSB_cpArbiterIgnore, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterIsFirstContact", JSB_cpArbiterIsFirstContact, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetElasticity", JSB_cpArbiterSetElasticity, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetFriction", JSB_cpArbiterSetFriction, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterSetSurfaceVelocity", JSB_cpArbiterSetSurfaceVelocity, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulse", JSB_cpArbiterTotalImpulse, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalImpulseWithFriction", JSB_cpArbiterTotalImpulseWithFriction, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "arbiterTotalKE", JSB_cpArbiterTotalKE, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "areaForCircle", JSB_cpAreaForCircle, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "areaForSegment", JSB_cpAreaForSegment, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBArea", JSB_cpBBArea, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBClampVect", JSB_cpBBClampVect, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBContainsBB", JSB_cpBBContainsBB, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBContainsVect", JSB_cpBBContainsVect, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBExpand", JSB_cpBBExpand, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBIntersects", JSB_cpBBIntersects, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBIntersectsSegment", JSB_cpBBIntersectsSegment, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBMerge", JSB_cpBBMerge, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBMergedArea", JSB_cpBBMergedArea, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBNew", JSB_cpBBNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBNewForCircle", JSB_cpBBNewForCircle, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBSegmentQuery", JSB_cpBBSegmentQuery, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bBWrapVect", JSB_cpBBWrapVect, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyActivate", JSB_cpBodyActivate, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyActivateStatic", JSB_cpBodyActivateStatic, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyApplyForce", JSB_cpBodyApplyForce, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyApplyImpulse", JSB_cpBodyApplyImpulse, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyDestroy", JSB_cpBodyDestroy, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyFree", JSB_cpBodyFree, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngVel", JSB_cpBodyGetAngVel, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngVelLimit", JSB_cpBodyGetAngVelLimit, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetAngle", JSB_cpBodyGetAngle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetForce", JSB_cpBodyGetForce, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetMass", JSB_cpBodyGetMass, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetMoment", JSB_cpBodyGetMoment, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetPos", JSB_cpBodyGetPos, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetRot", JSB_cpBodyGetRot, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetSpace", JSB_cpBodyGetSpace, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetTorque", JSB_cpBodyGetTorque, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVel", JSB_cpBodyGetVel, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelAtLocalPoint", JSB_cpBodyGetVelAtLocalPoint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelAtWorldPoint", JSB_cpBodyGetVelAtWorldPoint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyGetVelLimit", JSB_cpBodyGetVelLimit, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyInit", JSB_cpBodyInit, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyInitStatic", JSB_cpBodyInitStatic, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsRogue", JSB_cpBodyIsRogue, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsSleeping", JSB_cpBodyIsSleeping, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyIsStatic", JSB_cpBodyIsStatic, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyKineticEnergy", JSB_cpBodyKineticEnergy, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyLocal2World", JSB_cpBodyLocal2World, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyNew", JSB_cpBodyNew, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyNewStatic", JSB_cpBodyNewStatic, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyResetForces", JSB_cpBodyResetForces, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngVel", JSB_cpBodySetAngVel, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngVelLimit", JSB_cpBodySetAngVelLimit, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetAngle", JSB_cpBodySetAngle, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetForce", JSB_cpBodySetForce, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetMass", JSB_cpBodySetMass, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetMoment", JSB_cpBodySetMoment, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetPos", JSB_cpBodySetPos, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetTorque", JSB_cpBodySetTorque, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetVel", JSB_cpBodySetVel, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySetVelLimit", JSB_cpBodySetVelLimit, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySleep", JSB_cpBodySleep, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodySleepWithGroup", JSB_cpBodySleepWithGroup, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyUpdatePosition", JSB_cpBodyUpdatePosition, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyUpdateVelocity", JSB_cpBodyUpdateVelocity, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "bodyWorld2Local", JSB_cpBodyWorld2Local, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "boxShapeNew", JSB_cpBoxShapeNew, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "boxShapeNew2", JSB_cpBoxShapeNew2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeGetOffset", JSB_cpCircleShapeGetOffset, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeGetRadius", JSB_cpCircleShapeGetRadius, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "circleShapeNew", JSB_cpCircleShapeNew, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintActivateBodies", JSB_cpConstraintActivateBodies, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintDestroy", JSB_cpConstraintDestroy, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintFree", JSB_cpConstraintFree, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetA", JSB_cpConstraintGetA, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetB", JSB_cpConstraintGetB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetErrorBias", JSB_cpConstraintGetErrorBias, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetImpulse", JSB_cpConstraintGetImpulse, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetMaxBias", JSB_cpConstraintGetMaxBias, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetMaxForce", JSB_cpConstraintGetMaxForce, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintGetSpace", JSB_cpConstraintGetSpace, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetErrorBias", JSB_cpConstraintSetErrorBias, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetMaxBias", JSB_cpConstraintSetMaxBias, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "constraintSetMaxForce", JSB_cpConstraintSetMaxForce, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetDamping", JSB_cpDampedRotarySpringGetDamping, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetRestAngle", JSB_cpDampedRotarySpringGetRestAngle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringGetStiffness", JSB_cpDampedRotarySpringGetStiffness, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringNew", JSB_cpDampedRotarySpringNew, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetDamping", JSB_cpDampedRotarySpringSetDamping, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetRestAngle", JSB_cpDampedRotarySpringSetRestAngle, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedRotarySpringSetStiffness", JSB_cpDampedRotarySpringSetStiffness, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr1", JSB_cpDampedSpringGetAnchr1, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetAnchr2", JSB_cpDampedSpringGetAnchr2, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetDamping", JSB_cpDampedSpringGetDamping, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetRestLength", JSB_cpDampedSpringGetRestLength, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringGetStiffness", JSB_cpDampedSpringGetStiffness, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringNew", JSB_cpDampedSpringNew, 7, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr1", JSB_cpDampedSpringSetAnchr1, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetAnchr2", JSB_cpDampedSpringSetAnchr2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetDamping", JSB_cpDampedSpringSetDamping, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetRestLength", JSB_cpDampedSpringSetRestLength, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "dampedSpringSetStiffness", JSB_cpDampedSpringSetStiffness, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointGetPhase", JSB_cpGearJointGetPhase, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointGetRatio", JSB_cpGearJointGetRatio, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointNew", JSB_cpGearJointNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointSetPhase", JSB_cpGearJointSetPhase, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "gearJointSetRatio", JSB_cpGearJointSetRatio, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetAnchr2", JSB_cpGrooveJointGetAnchr2, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveA", JSB_cpGrooveJointGetGrooveA, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointGetGrooveB", JSB_cpGrooveJointGetGrooveB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointNew", JSB_cpGrooveJointNew, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetAnchr2", JSB_cpGrooveJointSetAnchr2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveA", JSB_cpGrooveJointSetGrooveA, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "grooveJointSetGrooveB", JSB_cpGrooveJointSetGrooveB, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "initChipmunk", JSB_cpInitChipmunk, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForBox", JSB_cpMomentForBox, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForBox2", JSB_cpMomentForBox2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForCircle", JSB_cpMomentForCircle, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "momentForSegment", JSB_cpMomentForSegment, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr1", JSB_cpPinJointGetAnchr1, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetAnchr2", JSB_cpPinJointGetAnchr2, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointGetDist", JSB_cpPinJointGetDist, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointNew", JSB_cpPinJointNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr1", JSB_cpPinJointSetAnchr1, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetAnchr2", JSB_cpPinJointSetAnchr2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pinJointSetDist", JSB_cpPinJointSetDist, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr1", JSB_cpPivotJointGetAnchr1, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointGetAnchr2", JSB_cpPivotJointGetAnchr2, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointNew", JSB_cpPivotJointNew, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointNew2", JSB_cpPivotJointNew2, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr1", JSB_cpPivotJointSetAnchr1, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "pivotJointSetAnchr2", JSB_cpPivotJointSetAnchr2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "polyShapeGetNumVerts", JSB_cpPolyShapeGetNumVerts, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "polyShapeGetVert", JSB_cpPolyShapeGetVert, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetAngle", JSB_cpRatchetJointGetAngle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetPhase", JSB_cpRatchetJointGetPhase, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointGetRatchet", JSB_cpRatchetJointGetRatchet, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointNew", JSB_cpRatchetJointNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetAngle", JSB_cpRatchetJointSetAngle, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetPhase", JSB_cpRatchetJointSetPhase, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "ratchetJointSetRatchet", JSB_cpRatchetJointSetRatchet, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "resetShapeIdCounter", JSB_cpResetShapeIdCounter, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMax", JSB_cpRotaryLimitJointGetMax, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointGetMin", JSB_cpRotaryLimitJointGetMin, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointNew", JSB_cpRotaryLimitJointNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMax", JSB_cpRotaryLimitJointSetMax, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "rotaryLimitJointSetMin", JSB_cpRotaryLimitJointSetMin, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetA", JSB_cpSegmentShapeGetA, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetB", JSB_cpSegmentShapeGetB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetNormal", JSB_cpSegmentShapeGetNormal, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeGetRadius", JSB_cpSegmentShapeGetRadius, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeNew", JSB_cpSegmentShapeNew, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "segmentShapeSetNeighbors", JSB_cpSegmentShapeSetNeighbors, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeCacheBB", JSB_cpShapeCacheBB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeDestroy", JSB_cpShapeDestroy, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeFree", JSB_cpShapeFree, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetBB", JSB_cpShapeGetBB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetBody", JSB_cpShapeGetBody, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetCollisionType", JSB_cpShapeGetCollisionType, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetElasticity", JSB_cpShapeGetElasticity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetFriction", JSB_cpShapeGetFriction, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetGroup", JSB_cpShapeGetGroup, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetLayers", JSB_cpShapeGetLayers, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSensor", JSB_cpShapeGetSensor, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSpace", JSB_cpShapeGetSpace, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeGetSurfaceVelocity", JSB_cpShapeGetSurfaceVelocity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapePointQuery", JSB_cpShapePointQuery, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetBody", JSB_cpShapeSetBody, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetCollisionType", JSB_cpShapeSetCollisionType, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetElasticity", JSB_cpShapeSetElasticity, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetFriction", JSB_cpShapeSetFriction, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetGroup", JSB_cpShapeSetGroup, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetLayers", JSB_cpShapeSetLayers, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetSensor", JSB_cpShapeSetSensor, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeSetSurfaceVelocity", JSB_cpShapeSetSurfaceVelocity, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "shapeUpdate", JSB_cpShapeUpdate, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorGetRate", JSB_cpSimpleMotorGetRate, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorNew", JSB_cpSimpleMotorNew, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "simpleMotorSetRate", JSB_cpSimpleMotorSetRate, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr1", JSB_cpSlideJointGetAnchr1, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetAnchr2", JSB_cpSlideJointGetAnchr2, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetMax", JSB_cpSlideJointGetMax, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointGetMin", JSB_cpSlideJointGetMin, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointNew", JSB_cpSlideJointNew, 6, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr1", JSB_cpSlideJointSetAnchr1, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetAnchr2", JSB_cpSlideJointSetAnchr2, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetMax", JSB_cpSlideJointSetMax, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "slideJointSetMin", JSB_cpSlideJointSetMin, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceActivateShapesTouchingShape", JSB_cpSpaceActivateShapesTouchingShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddBody", JSB_cpSpaceAddBody, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddConstraint", JSB_cpSpaceAddConstraint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddShape", JSB_cpSpaceAddShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceAddStaticShape", JSB_cpSpaceAddStaticShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsBody", JSB_cpSpaceContainsBody, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsConstraint", JSB_cpSpaceContainsConstraint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceContainsShape", JSB_cpSpaceContainsShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceDestroy", JSB_cpSpaceDestroy, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceFree", JSB_cpSpaceFree, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionBias", JSB_cpSpaceGetCollisionBias, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionPersistence", JSB_cpSpaceGetCollisionPersistence, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCollisionSlop", JSB_cpSpaceGetCollisionSlop, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetCurrentTimeStep", JSB_cpSpaceGetCurrentTimeStep, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetDamping", JSB_cpSpaceGetDamping, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetEnableContactGraph", JSB_cpSpaceGetEnableContactGraph, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetGravity", JSB_cpSpaceGetGravity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetIdleSpeedThreshold", JSB_cpSpaceGetIdleSpeedThreshold, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetIterations", JSB_cpSpaceGetIterations, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetSleepTimeThreshold", JSB_cpSpaceGetSleepTimeThreshold, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceGetStaticBody", JSB_cpSpaceGetStaticBody, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceInit", JSB_cpSpaceInit, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceIsLocked", JSB_cpSpaceIsLocked, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceNew", JSB_cpSpaceNew, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spacePointQueryFirst", JSB_cpSpacePointQueryFirst, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexShape", JSB_cpSpaceReindexShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexShapesForBody", JSB_cpSpaceReindexShapesForBody, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceReindexStatic", JSB_cpSpaceReindexStatic, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveBody", JSB_cpSpaceRemoveBody, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveConstraint", JSB_cpSpaceRemoveConstraint, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveShape", JSB_cpSpaceRemoveShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceRemoveStaticShape", JSB_cpSpaceRemoveStaticShape, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionBias", JSB_cpSpaceSetCollisionBias, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionPersistence", JSB_cpSpaceSetCollisionPersistence, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetCollisionSlop", JSB_cpSpaceSetCollisionSlop, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetDamping", JSB_cpSpaceSetDamping, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetEnableContactGraph", JSB_cpSpaceSetEnableContactGraph, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetGravity", JSB_cpSpaceSetGravity, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetIdleSpeedThreshold", JSB_cpSpaceSetIdleSpeedThreshold, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetIterations", JSB_cpSpaceSetIterations, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceSetSleepTimeThreshold", JSB_cpSpaceSetSleepTimeThreshold, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceStep", JSB_cpSpaceStep, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "spaceUseSpatialHash", JSB_cpSpaceUseSpatialHash, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fabs", JSB_cpfabs, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fclamp", JSB_cpfclamp, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fclamp01", JSB_cpfclamp01, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "flerp", JSB_cpflerp, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "flerpconst", JSB_cpflerpconst, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fmax", JSB_cpfmax, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "fmin", JSB_cpfmin, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vadd", JSB_cpvadd, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vclamp", JSB_cpvclamp, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vcross", JSB_cpvcross, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdist", JSB_cpvdist, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdistsq", JSB_cpvdistsq, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vdot", JSB_cpvdot, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "veql", JSB_cpveql, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vforangle", JSB_cpvforangle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlength", JSB_cpvlength, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlengthsq", JSB_cpvlengthsq, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlerp", JSB_cpvlerp, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vlerpconst", JSB_cpvlerpconst, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vmult", JSB_cpvmult, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnear", JSB_cpvnear, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vneg", JSB_cpvneg, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnormalize", JSB_cpvnormalize, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vnormalize_safe", JSB_cpvnormalize_safe, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vperp", JSB_cpvperp, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vproject", JSB_cpvproject, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vrotate", JSB_cpvrotate, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vrperp", JSB_cpvrperp, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vslerp", JSB_cpvslerp, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vslerpconst", JSB_cpvslerpconst, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vsub", JSB_cpvsub, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vtoangle", JSB_cpvtoangle, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); +JS_DefineFunction(cx, chipmunk, "vunrotate", JSB_cpvunrotate, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); #endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp index 6a31f800e6..292a54e557 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_registration.cpp @@ -52,17 +52,17 @@ void jsb_register_chipmunk(JSContext* cx, JSObject *object) #include "js_bindings_chipmunk_functions_registration.h" // manual - JS_DefineFunction(cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "spaceAddCollisionHandler", JSB_cpSpaceAddCollisionHandler, 8, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "spaceRemoveCollisionHandler", JSB_cpSpaceRemoveCollisionHandler, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "arbiterGetBodies", JSB_cpArbiterGetBodies, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "arbiterGetShapes", JSB_cpArbiterGetShapes, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "bodyGetUserData", JSB_cpBodyGetUserData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "bodySetUserData", JSB_cpBodySetUserData, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); - JS_DefineFunction(cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "areaForPoly", JSB_cpAreaForPoly, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "momentForPoly", JSB_cpMomentForPoly, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "centroidForPoly", JSB_cpCentroidForPoly, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); + JS_DefineFunction(cx, chipmunk, "recenterPoly", JSB_cpRecenterPoly, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE ); register_CCPhysicsSprite(cx, object); register_CCPhysicsDebugNode(cx, object); } diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 8ac72cc7c1..48e0a33cff 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -3194d28204e71875735934ee3207961ec14e655a \ No newline at end of file +1cd78fedc4d2dc2609f92a179cd60ac4ce33ca08 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index 4eeff5392e..56f7d926e1 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -232,9 +232,9 @@ extern JSObject* jsb_ArmatureDataManager_prototype; void register_all_cocos2dx_studio_manual(JSContext* cx, JSObject* global) { - JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setMovementEventCallFunc", js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setMovementEventCallFunc", js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setFrameEventCallFunc", js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_ArmatureAnimation_prototype, "setFrameEventCallFunc", js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_ArmatureDataManager_prototype, "addArmatureFileInfoAsync", jsb_Animation_addArmatureFileInfoAsyncCallFunc, 3, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_ArmatureDataManager_prototype, "addArmatureFileInfoAsync", jsb_Animation_addArmatureFileInfoAsyncCallFunc, 3, JSPROP_ENUMERATE | JSPROP_PERMANENT); } \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp index f72be9c54b..963489a41d 100644 --- a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp @@ -788,12 +788,12 @@ extern JSObject* jsb_Control_prototype; void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) { - JS_DefineFunction(cx, jsb_ScrollView_prototype, "setDelegate", js_cocos2dx_CCScrollView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_TableView_prototype, "setDelegate", js_cocos2dx_CCTableView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_TableView_prototype, "setDataSource", js_cocos2dx_CCTableView_setDataSource, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_EditBox_prototype, "setDelegate", js_cocos2dx_CCEditBox_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_ScrollView_prototype, "setDelegate", js_cocos2dx_CCScrollView_setDelegate, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_TableView_prototype, "setDelegate", js_cocos2dx_CCTableView_setDelegate, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_TableView_prototype, "setDataSource", js_cocos2dx_CCTableView_setDataSource, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_EditBox_prototype, "setDelegate", js_cocos2dx_CCEditBox_setDelegate, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_ENUMERATE | JSPROP_PERMANENT); JSObject *tmpObj = JSVAL_TO_OBJECT(anonEvaluate(cx, global, "(function () { return cc.TableView; })()")); JS_DefineFunction(cx, tmpObj, "create", js_cocos2dx_CCTableView_create, 3, JSPROP_READONLY | JSPROP_PERMANENT); diff --git a/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp b/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp index 32b4956a16..3c070fa5f6 100644 --- a/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp +++ b/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp @@ -299,19 +299,19 @@ extern JSObject* jsb_UIListView_prototype; void register_all_cocos2dx_gui_manual(JSContext* cx, JSObject* global) { - JS_DefineFunction(cx, jsb_UIWidget_prototype, "addTouchEventListener", js_cocos2dx_UIWidget_addTouchEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UIWidget_prototype, "addTouchEventListener", js_cocos2dx_UIWidget_addTouchEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UICheckBox_prototype, "addEventListenerCheckBox", js_cocos2dx_UICheckBox_addEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UICheckBox_prototype, "addEventListenerCheckBox", js_cocos2dx_UICheckBox_addEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UISlider_prototype, "addEventListenerSlider", js_cocos2dx_UISlider_addEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UISlider_prototype, "addEventListenerSlider", js_cocos2dx_UISlider_addEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UITextField_prototype, "addEventListenerTextField", js_cocos2dx_UITextField_addEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UITextField_prototype, "addEventListenerTextField", js_cocos2dx_UITextField_addEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UIPageView_prototype, "addEventListenerPageView", js_cocos2dx_UIPageView_addEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UIPageView_prototype, "addEventListenerPageView", js_cocos2dx_UIPageView_addEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UIListView_prototype, "addEventListenerListView", js_cocos2dx_UIListView_addEventListener, 2, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UIListView_prototype, "addEventListenerListView", js_cocos2dx_UIListView_addEventListener, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UILayoutParameter_prototype, "setMargin", js_cocos2dx_LayoutParameter_setMargin, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UILayoutParameter_prototype, "setMargin", js_cocos2dx_LayoutParameter_setMargin, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); - JS_DefineFunction(cx, jsb_UILayoutParameter_prototype, "getMargin", js_cocos2dx_LayoutParameter_getMargin, 0, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_UILayoutParameter_prototype, "getMargin", js_cocos2dx_LayoutParameter_getMargin, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); } \ No newline at end of file From df1fca3279df747e544038e0fefccfac17ce0292 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 26 Nov 2013 11:38:55 +0800 Subject: [PATCH 37/75] issue #2771: refactor some functions and delete PHYSICS_INFINITY macro. --- cocos/physics/CCPhysicsBody.cpp | 28 +++++++------- cocos/physics/CCPhysicsBody.h | 16 ++++---- cocos/physics/CCPhysicsSetting.h | 4 +- cocos/physics/CCPhysicsShape.cpp | 38 +++++++++---------- cocos/physics/CCPhysicsWorld.cpp | 3 -- .../Classes/PhysicsTest/PhysicsTest.cpp | 8 ++-- 6 files changed, 46 insertions(+), 51 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 69772073ac..f47d8b1acd 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -315,8 +315,8 @@ void PhysicsBody::setDynamic(bool dynamic) } // avoid incorrect collion simulation. - cpBodySetMass(_info->getBody(), PHYSICS_INFINITY); - cpBodySetMoment(_info->getBody(), PHYSICS_INFINITY); + cpBodySetMass(_info->getBody(), INFINITY); + cpBodySetMoment(_info->getBody(), INFINITY); cpBodySetVel(_info->getBody(), cpvzero); cpBodySetAngVel(_info->getBody(), 0.0f); } @@ -328,7 +328,7 @@ void PhysicsBody::setRotationEnable(bool enable) { if (_rotationEnable != enable) { - cpBodySetMoment(_info->getBody(), enable ? _moment : PHYSICS_INFINITY); + cpBodySetMoment(_info->getBody(), enable ? _moment : INFINITY); _rotationEnable = enable; } } @@ -454,9 +454,9 @@ void PhysicsBody::setMass(float mass) _massDefault = false; // update density - if (_mass == PHYSICS_INFINITY) + if (_mass == INFINITY) { - _density = PHYSICS_INFINITY; + _density = INFINITY; } else { @@ -478,17 +478,17 @@ void PhysicsBody::setMass(float mass) void PhysicsBody::addMass(float mass) { - if (mass == PHYSICS_INFINITY) + if (mass == INFINITY) { - _mass = PHYSICS_INFINITY; + _mass = INFINITY; _massDefault = false; - _density = PHYSICS_INFINITY; + _density = INFINITY; } - else if (mass == -PHYSICS_INFINITY) + else if (mass == -INFINITY) { return; } - else if (_mass != PHYSICS_INFINITY) + else if (_mass != INFINITY) { if (_massDefault) { @@ -524,13 +524,13 @@ void PhysicsBody::addMass(float mass) void PhysicsBody::addMoment(float moment) { - if (moment == PHYSICS_INFINITY) + if (moment == INFINITY) { // if moment is INFINITY, the moment of the body will become INFINITY - _moment = PHYSICS_INFINITY; + _moment = INFINITY; _momentDefault = false; } - else if (moment == -PHYSICS_INFINITY) + else if (moment == -INFINITY) { // if moment is -INFINITY, it won't change return; @@ -538,7 +538,7 @@ void PhysicsBody::addMoment(float moment) else { // if moment of the body is INFINITY is has no effect - if (_moment != PHYSICS_INFINITY) + if (_moment != INFINITY) { if (_momentDefault) { diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 7c2b79b9ba..f05222fb03 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -205,16 +205,16 @@ public: /** * @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. + * @note if you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to INFINITY, it will cause some unexpected result, please use addMass() instead. */ void setMass(float mass); /** get the body mass. */ inline float getMass() const { 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 of the body) == INFINITY, it remains. + * if mass == INFINITY, _mass will be INFINITY. + * if mass == -INFINITY, _mass will not change. * if mass + _mass <= 0, _mass will equal to MASS_DEFAULT(1.0) * other wise, mass = mass + _mass; */ @@ -222,16 +222,16 @@ public: /** * @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. + * @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to INFINITY, it will cause some unexpected result, please use addMoment() instead. */ void setMoment(float moment); /** get the body moment of inertia. */ inline float getMoment(float moment) const { 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 of the body) == INFINITY, it remains. + * if moment == INFINITY, _moment will be INFINITY. + * if moment == -INFINITY, _moment will not change. * if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0) * other wise, moment = moment + _moment; */ diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h index 64071e4425..a3ad849379 100644 --- a/cocos/physics/CCPhysicsSetting.h +++ b/cocos/physics/CCPhysicsSetting.h @@ -29,7 +29,7 @@ #define CC_PHYSICS_BOX2D 1 #define CC_PHYSICS_CHIPMUNK 2 -#define CC_USE_BOX2D +#define CC_USE_CHIPMUNK #ifdef CC_USE_BOX2D #define CC_PHYSICS_ENGINE CC_PHYSICS_BOX2D @@ -45,8 +45,6 @@ namespace cocos2d { - extern const float PHYSICS_INFINITY; - class Point; typedef Point Vect; diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index e41b04fc2e..c48b1c6d09 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -205,9 +205,9 @@ void PhysicsShape::setDensity(float density) _material.density = density; - if (_material.density == PHYSICS_INFINITY) + if (_material.density == INFINITY) { - setMass(PHYSICS_INFINITY); + setMass(INFINITY); }else if (_area > 0) { setMass(PhysicsHelper::float2cpfloat(_material.density * _area)); @@ -313,7 +313,7 @@ bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = _info->add(shape); _area = calculateDefaultArea(); - _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _mass = material.density == INFINITY ? INFINITY : material.density * _area; _moment = calculateDefaultMoment(); setMaterial(material); @@ -330,7 +330,7 @@ float PhysicsShapeCircle::calculateArea(float radius) float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Point& offset) { - return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + return mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), 0, PhysicsHelper::float2cpfloat(radius), @@ -346,7 +346,7 @@ float PhysicsShapeCircle::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + return _mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), 0, cpCircleShapeGetRadius(shape), @@ -392,8 +392,8 @@ bool PhysicsShapeEdgeSegment::init(const Point& a, const Point& b, const Physics _info->add(shape); - _mass = PHYSICS_INFINITY; - _moment = PHYSICS_INFINITY; + _mass = INFINITY; + _moment = INFINITY; _center = a.getMidpoint(b); @@ -454,7 +454,7 @@ bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = _offset = offset; _area = calculateDefaultArea(); - _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _mass = material.density == INFINITY ? INFINITY : material.density * _area; _moment = calculateDefaultMoment(); setMaterial(material); @@ -483,7 +483,7 @@ float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Point {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} }; - return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + return mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(PhysicsHelper::float2cpfloat(mass), 4, vec, @@ -499,7 +499,7 @@ float PhysicsShapeBox::calculateDefaultArea() float PhysicsShapeBox::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + return _mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } @@ -546,7 +546,7 @@ bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMate _info->add(shape); _area = calculateDefaultArea(); - _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; + _mass = material.density == INFINITY ? INFINITY : material.density * _area; _moment = calculateDefaultMoment(); _center = PhysicsHelper::cpv2point(cpCentroidForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); @@ -572,7 +572,7 @@ float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - float moment = mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + float moment = mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(mass, count, vecs, PhysicsHelper::point2cpv(offset))); CC_SAFE_DELETE_ARRAY(vecs); @@ -588,7 +588,7 @@ float PhysicsShapePolygon::calculateDefaultArea() float PhysicsShapePolygon::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY + return _mass == INFINITY ? INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } @@ -650,8 +650,8 @@ bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material CC_BREAK_IF(i < 4); _offset = offset; - _mass = PHYSICS_INFINITY; - _moment = PHYSICS_INFINITY; + _mass = INFINITY; + _moment = INFINITY; setMaterial(material); @@ -700,8 +700,8 @@ bool PhysicsShapeEdgePolygon::init(const Point* points, int count, const Physics CC_BREAK_IF(i < count); - _mass = PHYSICS_INFINITY; - _moment = PHYSICS_INFINITY; + _mass = INFINITY; + _moment = INFINITY; setMaterial(material); @@ -761,8 +761,8 @@ bool PhysicsShapeEdgeChain::init(const Point* points, int count, const PhysicsMa CC_SAFE_DELETE_ARRAY(vec); CC_BREAK_IF(i < count); - _mass = PHYSICS_INFINITY; - _moment = PHYSICS_INFINITY; + _mass = INFINITY; + _moment = INFINITY; setMaterial(material); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index a8ca7a8d23..a7e17ff71e 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -65,9 +65,6 @@ NS_CC_BEGIN extern const char* PHYSICSCONTACT_EVENT_NAME; #if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - -const float PHYSICS_INFINITY = INFINITY; - namespace { typedef struct RayCastCallbackInfo diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 4acaf61418..89197f3fec 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -384,7 +384,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) if (body != nullptr) { Node* mouse = Node::create(); - mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); + mouse->setPhysicsBody(PhysicsBody::create(INFINITY, INFINITY)); mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); @@ -444,7 +444,7 @@ void PhysicsDemoLogoSmash::onEnter() 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); - ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); + ball->getPhysicsBody()->setMoment(INFINITY); _ball->addChild(ball); @@ -453,7 +453,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); + auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -835,7 +835,7 @@ void PhysicsDemoPump::onEnter() auto body = PhysicsBody::create(); body->setDynamic(false); - PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); + PhysicsMaterial staticMaterial(INFINITY, 0, 0.5f); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); From 881d43fe3b0f2b20abad8c42cffb1142e7dc8375 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 26 Nov 2013 11:58:01 +0800 Subject: [PATCH 38/75] add proceed java compilation and generate apk. --- build/android-build.py | 56 ++++++++++++++++++++++---- tools/travis-scripts/before-install.sh | 10 ++--- 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index 34ac6010d9..77189ee5f9 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -15,8 +15,10 @@ ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES def usage(): - print """%s [-n ndk-build-parameter] target. + print """%s [-n ndk-build-parameter] [-p android-platform] [-b build-mode] target. +Valid android-platform are:[10|11|12|13|14|15|16|17] +Valid build-mode are:[debug|release] Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon |crystalcraze|moonwarriors|testjavascript|watermelonwithme] @@ -33,6 +35,18 @@ def check_environment_variables(): sys.exit(1) return NDK_ROOT + +def check_environment_variables_sdk(): + ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building + ''' + + try: + SDK_ROOT = os.environ['ANDROID_SDK_ROOT'] + except Exception: + print "ANDROID_SDK_ROOT not defined. Please define ANDROID_SDK_ROOT in your environment" + sys.exit(1) + + return SDK_ROOT def select_toolchain_version(): '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when @@ -81,7 +95,7 @@ def caculate_built_samples(args): targets = set(targets) return list(targets) -def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): +def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,android_platform,build_mode): ndk_path = os.path.join(ndk_root, "ndk-build") @@ -97,7 +111,19 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param): else: command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) if os.system(command) != 0: - raise Exception("Build project [ " + app_android_root + " ] fails!") + raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") + elif android_platform is not None: + sdk_tool_path = os.path.join(sdk_root, "tools/android") + cocoslib_path = os.path.join(cocos_root, "cocos/2d/platform/android/java") + command = '%s update lib-project -t %s -p %s' % (sdk_tool_path,android_platform,cocoslib_path) + if os.system(command) != 0: + raise Exception("update cocos lib-project [ " + cocoslib_path + " ] fails!") + command = '%s update project -t %s -p %s -s' % (sdk_tool_path,android_platform,app_android_root) + if os.system(command) != 0: + raise Exception("update project [ " + app_android_root + " ] fails!") + buildfile_path = os.path.join(app_android_root, "build.xml") + command = 'ant clean %s -f %s -Dsdk.dir=%s' % (build_mode,buildfile_path,sdk_root) + os.system(command) def copy_files(src, dst): @@ -169,15 +195,29 @@ def copy_resources(target, app_android_root): resources_dir = os.path.join(app_android_root, "../../../Cpp/TestCpp/Resources") copy_files(resources_dir, assets_dir) -def build_samples(target,ndk_build_param): +def build_samples(target,ndk_build_param,android_platform,build_mode): ndk_root = check_environment_variables() + sdk_root = None select_toolchain_version() build_targets = caculate_built_samples(target) current_dir = os.path.dirname(os.path.realpath(__file__)) cocos_root = os.path.join(current_dir, "..") - + + if android_platform is not None: + sdk_root = check_environment_variables_sdk() + if android_platform.isdigit(): + android_platform = 'android-'+android_platform + else: + print 'please use vaild android platform' + exit(1) + + if build_mode is None: + build_mode = 'debug' + elif build_mode != 'release': + build_mode = 'debug' + app_android_root = '' for target in build_targets: if target == 'hellocpp': @@ -207,7 +247,7 @@ def build_samples(target,ndk_build_param): continue copy_resources(target, app_android_root) - do_build(cocos_root, ndk_root, app_android_root, ndk_build_param) + do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,android_platform,build_mode) # -------------- main -------------- if __name__ == '__main__': @@ -215,13 +255,15 @@ if __name__ == '__main__': #parse the params parser = OptionParser() parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build') + parser.add_option("-p", "--platform", dest="android_platform", help='parameter for android-update') + parser.add_option("-b", "--build", dest="build_mode", help='the build mode for java project,debug or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') (opts, args) = parser.parse_args() if len(args) == 0: usage() else: try: - build_samples(args, opts.ndk_build_param) + build_samples(args, opts.ndk_build_param,opts.android_platform,opts.build_mode) except Exception as e: print e sys.exit(1) diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh index 79154e4604..acfdd36e12 100755 --- a/tools/travis-scripts/before-install.sh +++ b/tools/travis-scripts/before-install.sh @@ -21,12 +21,12 @@ install_android_ndk() else HOST_NAME="linux" fi - echo "Download android-ndk-r8e-${HOST_NAME}-x86_64.tar.bz2 ..." - curl -O http://dl.google.com/android/ndk/android-ndk-r8e-${HOST_NAME}-x86_64.tar.bz2 - echo "Decompress android-ndk-r8e-${HOST_NAME}-x86_64.tar.bz2 ..." - tar xjf android-ndk-r8e-${HOST_NAME}-x86_64.tar.bz2 + echo "Download android-ndk-r9b-${HOST_NAME}-x86_64.tar.bz2 ..." + curl -O http://dl.google.com/android/ndk/android-ndk-r9b-${HOST_NAME}-x86_64.tar.bz2 + echo "Decompress android-ndk-r9b-${HOST_NAME}-x86_64.tar.bz2 ..." + tar xjf android-ndk-r9b-${HOST_NAME}-x86_64.tar.bz2 # Rename ndk - mv android-ndk-r8e android-ndk + mv android-ndk-r9b android-ndk } install_llvm() From 99d904363a5fd7160f143af2c2e99f26ea830ed2 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 26 Nov 2013 13:47:42 +0800 Subject: [PATCH 39/75] issue #2771: delete all the box2d implementation in physics parts. --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCLayer.h | 1 - cocos/2d/CCNode.h | 1 - cocos/2d/ccConfig.h | 9 ++ cocos/physics/CCPhysicsBody.cpp | 17 ---- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsContact.cpp | 10 --- cocos/physics/CCPhysicsContact.h | 1 - cocos/physics/CCPhysicsJoint.cpp | 14 --- cocos/physics/CCPhysicsJoint.h | 1 - cocos/physics/CCPhysicsSetting.h | 58 ------------ cocos/physics/CCPhysicsShape.cpp | 11 --- cocos/physics/CCPhysicsShape.h | 1 - cocos/physics/CCPhysicsWorld.cpp | 17 ---- cocos/physics/CCPhysicsWorld.h | 1 - .../physics/box2d/CCPhysicsBodyInfo_box2d.cpp | 39 -------- cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h | 54 ----------- .../box2d/CCPhysicsContactInfo_box2d.cpp | 40 --------- .../box2d/CCPhysicsContactInfo_box2d.h | 45 ---------- cocos/physics/box2d/CCPhysicsHelper_box2d.h | 46 ---------- .../box2d/CCPhysicsJointInfo_box2d.cpp | 41 --------- .../physics/box2d/CCPhysicsJointInfo_box2d.h | 46 ---------- .../box2d/CCPhysicsShapeInfo_box2d.cpp | 40 --------- .../physics/box2d/CCPhysicsShapeInfo_box2d.h | 47 ---------- .../box2d/CCPhysicsWorldInfo_box2d.cpp | 89 ------------------- .../physics/box2d/CCPhysicsWorldInfo_box2d.h | 66 -------------- .../chipmunk/CCPhysicsBodyInfo_chipmunk.cpp | 4 +- .../chipmunk/CCPhysicsBodyInfo_chipmunk.h | 5 +- .../CCPhysicsContactInfo_chipmunk.cpp | 4 +- .../chipmunk/CCPhysicsContactInfo_chipmunk.h | 5 +- .../chipmunk/CCPhysicsHelper_chipmunk.h | 5 +- .../chipmunk/CCPhysicsJointInfo_chipmunk.cpp | 4 +- .../chipmunk/CCPhysicsJointInfo_chipmunk.h | 5 +- .../chipmunk/CCPhysicsShapeInfo_chipmunk.cpp | 4 +- .../chipmunk/CCPhysicsShapeInfo_chipmunk.h | 5 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 5 +- .../chipmunk/CCPhysicsWorldInfo_chipmunk.h | 6 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 2 +- 38 files changed, 36 insertions(+), 717 deletions(-) delete mode 100644 cocos/physics/CCPhysicsSetting.h delete mode 100644 cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp delete mode 100644 cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h delete mode 100644 cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp delete mode 100644 cocos/physics/box2d/CCPhysicsContactInfo_box2d.h delete mode 100644 cocos/physics/box2d/CCPhysicsHelper_box2d.h delete mode 100644 cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp delete mode 100644 cocos/physics/box2d/CCPhysicsJointInfo_box2d.h delete mode 100644 cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp delete mode 100644 cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h delete mode 100644 cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp delete mode 100644 cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 3143ef614d..f436fb8bc9 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -820d4d91d031eb7dde2f974508e61dac29d1a8d1 \ No newline at end of file +5221e6a74126a0c87cb3637082cf9035157a97f0 \ No newline at end of file diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 2aafa9a895..377302f5bd 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -33,7 +33,6 @@ THE SOFTWARE. #ifdef EMSCRIPTEN #include "CCGLBufferedNode.h" #endif // EMSCRIPTEN -#include "CCPhysicsSetting.h" #include "CCEventKeyboard.h" diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index ba9151884b..655c60d277 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -38,7 +38,6 @@ #include "CCScriptSupport.h" #include "CCProtocols.h" #include "CCEventDispatcher.h" -#include "CCPhysicsSetting.h" #include diff --git a/cocos/2d/ccConfig.h b/cocos/2d/ccConfig.h index f801066bfe..5cf5af7bdc 100644 --- a/cocos/2d/ccConfig.h +++ b/cocos/2d/ccConfig.h @@ -266,4 +266,13 @@ To enable set it to a value different than 0. Disabled by default. #define CC_LUA_ENGINE_DEBUG 0 #endif +#ifdef CC_USE_PHYSICS +#define PHYSICS_CONTACT_POINT_MAX 4 +namespace cocos2d +{ + class Point; + typedef Point Vect; +} +#endif + #endif // __CCCONFIG_H__ diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index f47d8b1acd..ec8295b873 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -27,32 +27,20 @@ #include #include -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" -#elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) -#include "Box2D.h" -#endif #include "CCPhysicsShape.h" #include "CCPhysicsJoint.h" #include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" -#include "box2d/CCPhysicsBodyInfo_box2d.h" #include "chipmunk/CCPhysicsJointInfo_chipmunk.h" -#include "box2d/CCPhysicsJointInfo_box2d.h" #include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" -#include "box2d/CCPhysicsWorldInfo_box2d.h" #include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" -#include "box2d/CCPhysicsShapeInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" -#include "box2d/CCPhysicsHelper_box2d.h" NS_CC_BEGIN - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - namespace { static const float MASS_DEFAULT = 1.0; @@ -811,11 +799,6 @@ Point PhysicsBody::local2World(const Point& point) return PhysicsHelper::cpv2point(cpBodyLocal2World(_info->getBody(), PhysicsHelper::point2cpv(point))); } -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - - -#endif - NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index f05222fb03..731af4bbd0 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -25,9 +25,9 @@ #ifndef __CCPHYSICS_BODY_H__ #define __CCPHYSICS_BODY_H__ -#include "CCPhysicsSetting.h" #ifdef CC_USE_PHYSICS +#include "ccConfig.h" #include "CCObject.h" #include "CCGeometry.h" #include "CCArray.h" diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index 5fe324f3ed..e0233df958 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -23,19 +23,12 @@ ****************************************************************************/ #include "CCPhysicsContact.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 "chipmunk/CCPhysicsContactInfo_chipmunk.h" -#include "box2d/CCPhysicsContactInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" -#include "box2d/CCPhysicsHelper_box2d.h" #include "CCEventCustom.h" @@ -95,7 +88,6 @@ bool PhysicsContact::init(PhysicsShape* a, PhysicsShape* b) return false; } -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) void PhysicsContact::generateContactData() { if (_contactInfo == nullptr) @@ -497,8 +489,6 @@ EventListenerPhysicsContactWithGroup* EventListenerPhysicsContactWithGroup::clon CC_SAFE_DELETE(obj); return nullptr; } -#else -#endif NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 915937e1e6..40d9081653 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -25,7 +25,6 @@ #ifndef __CCPHYSICS_CONTACT_H__ #define __CCPHYSICS_CONTACT_H__ -#include "CCPhysicsSetting.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" diff --git a/cocos/physics/CCPhysicsJoint.cpp b/cocos/physics/CCPhysicsJoint.cpp index f28095cfa9..295560a9e6 100644 --- a/cocos/physics/CCPhysicsJoint.cpp +++ b/cocos/physics/CCPhysicsJoint.cpp @@ -24,24 +24,15 @@ #include "CCPhysicsJoint.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 "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsJointInfo_chipmunk.h" -#include "box2d/CCPhysicsJointInfo_box2d.h" #include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" -#include "box2d/CCPhysicsBodyInfo_box2d.h" #include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" -#include "box2d/CCPhysicsShapeInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" -#include "box2d/CCPhysicsHelper_box2d.h" #include "CCNode.h" NS_CC_BEGIN @@ -146,7 +137,6 @@ PhysicsJointDistance::~PhysicsJointDistance() } -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) PhysicsBodyInfo* PhysicsJoint::getBodyInfo(PhysicsBody* body) const { return body->_info; @@ -371,9 +361,5 @@ bool PhysicsJointDistance::init(PhysicsBody* a, PhysicsBody* b, const Point& anc return false; } -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#endif - NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsJoint.h b/cocos/physics/CCPhysicsJoint.h index 4cb2abc5a2..45e038a774 100644 --- a/cocos/physics/CCPhysicsJoint.h +++ b/cocos/physics/CCPhysicsJoint.h @@ -25,7 +25,6 @@ #ifndef __CCPHYSICS_JOINT_H__ #define __CCPHYSICS_JOINT_H__ -#include "CCPhysicsSetting.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" diff --git a/cocos/physics/CCPhysicsSetting.h b/cocos/physics/CCPhysicsSetting.h deleted file mode 100644 index a3ad849379..0000000000 --- a/cocos/physics/CCPhysicsSetting.h +++ /dev/null @@ -1,58 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_SETTING_H__ -#define __CCPHYSICS_SETTING_H__ - -#define CC_PHYSICS_UNKNOWN 0 -#define CC_PHYSICS_BOX2D 1 -#define CC_PHYSICS_CHIPMUNK 2 - -#define CC_USE_CHIPMUNK - -#ifdef CC_USE_BOX2D -#define CC_PHYSICS_ENGINE CC_PHYSICS_BOX2D -#elif defined(CC_USE_CHIPMUNK) -#define CC_PHYSICS_ENGINE CC_PHYSICS_CHIPMUNK -#else -#define CC_PHYSICS_ENGINE CC_PHYSICS_UNKNOWN -#endif - -#if (CC_PHYSICS_ENGINE != CC_PHYSICS_UNKNOWN) -#define CC_USE_PHYSICS -#endif - -namespace cocos2d -{ - class Point; - typedef Point Vect; - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) - static const long PHYSICS_CONTACT_POINT_MAX = 4; -#else - static const long PHYSICS_CONTACT_POINT_MAX = 2; -#endif -} - -#endif // __CCPHYSICS_SETTING_H__ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index c48b1c6d09..d40c7c14a4 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -27,19 +27,13 @@ #include -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "chipmunk.h" -#elif (CC_PHYSICS_ENGINE == CCPHYSICS_BOX2D) -#include "Box2D.h" -#endif #include "CCPhysicsBody.h" #include "CCPhysicsWorld.h" #include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" -#include "box2d/CCPhysicsBodyInfo_box2d.h" #include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" -#include "box2d/CCPhysicsShapeInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN @@ -195,7 +189,6 @@ PhysicsShapeEdgeSegment::~PhysicsShapeEdgeSegment() } -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) void PhysicsShape::setDensity(float density) { if (density < 0) @@ -810,10 +803,6 @@ bool PhysicsShape::containsPoint(const Point& point) const return false; } -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#endif - NS_CC_END #endif // CC_USE_PHYSICS diff --git a/cocos/physics/CCPhysicsShape.h b/cocos/physics/CCPhysicsShape.h index 9e038f1ea3..b97bb3cba6 100644 --- a/cocos/physics/CCPhysicsShape.h +++ b/cocos/physics/CCPhysicsShape.h @@ -25,7 +25,6 @@ #ifndef __CCPHYSICS_SHAPE_H__ #define __CCPHYSICS_SHAPE_H__ -#include "CCPhysicsSetting.h" #ifdef CC_USE_PHYSICS #include "CCObject.h" diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index a7e17ff71e..2dc696bde6 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -27,11 +27,7 @@ #include -#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" @@ -40,15 +36,10 @@ #include "CCPhysicsContact.h" #include "chipmunk/CCPhysicsWorldInfo_chipmunk.h" -#include "box2d/CCPhysicsWorldInfo_box2d.h" #include "chipmunk/CCPhysicsBodyInfo_chipmunk.h" -#include "box2d/CCPhysicsBodyInfo_box2d.h" #include "chipmunk/CCPhysicsShapeInfo_chipmunk.h" -#include "box2d/CCPhysicsShapeInfo_box2d.h" #include "chipmunk/CCPhysicsContactInfo_chipmunk.h" -#include "box2d/CCPhysicsContactInfo_box2d.h" #include "chipmunk/CCPhysicsJointInfo_chipmunk.h" -#include "box2d/CCPhysicsJointInfo_box2d.h" #include "chipmunk/CCPhysicsHelper_chipmunk.h" #include "CCDrawNode.h" @@ -64,7 +55,6 @@ NS_CC_BEGIN extern const char* PHYSICSCONTACT_EVENT_NAME; -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) namespace { typedef struct RayCastCallbackInfo @@ -537,10 +527,6 @@ void PhysicsDebugDraw::drawContact() } -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#endif - PhysicsWorld* PhysicsWorld::construct(Scene& scene) { PhysicsWorld * world = new PhysicsWorld(); @@ -573,15 +559,12 @@ bool PhysicsWorld::init(Scene& scene) _info->setGravity(_gravity); -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) cpSpaceSetDefaultCollisionHandler(_info->getSpace(), (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc, (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc, (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc, (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc, this); -#elif (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#endif return true; } while (false); diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index d176c1f56d..71f977c5f4 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -25,7 +25,6 @@ #ifndef __CCPHYSICS_WORLD_H__ #define __CCPHYSICS_WORLD_H__ -#include "CCPhysicsSetting.h" #ifdef CC_USE_PHYSICS #include diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp deleted file mode 100644 index 059619a264..0000000000 --- a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp +++ /dev/null @@ -1,39 +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 "CCPhysicsBodyInfo_box2d.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -NS_CC_BEGIN - -PhysicsBodyInfo::PhysicsBodyInfo() -{ -} - -PhysicsBodyInfo::~PhysicsBodyInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h b/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.h deleted file mode 100644 index c8af764432..0000000000 --- a/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_BODY_INFO_BOX2D_H__ -#define __CCPHYSICS_BODY_INFO_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPlatformMacros.h" -#include "Box2D.h" - -NS_CC_BEGIN - -class PhysicsBodyInfo -{ -public: - inline b2BodyDef& getBodyDef() { return _bodyDef; } - inline b2Body* getBody() { return _body; } - inline void setBody(b2Body* body) { _body = body; } - -private: - b2Body* _body; - b2BodyDef _bodyDef; - -private: - PhysicsBodyInfo(); - ~PhysicsBodyInfo(); -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_BODY_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp deleted file mode 100644 index 6efc851e3e..0000000000 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp +++ /dev/null @@ -1,40 +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 "CCPhysicsContactInfo_box2d.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPhysicsContact.h" -NS_CC_BEGIN - -PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) -{ -} - -PhysicsContactInfo::~PhysicsContactInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h b/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h deleted file mode 100644 index 791a411f32..0000000000 --- a/cocos/physics/box2d/CCPhysicsContactInfo_box2d.h +++ /dev/null @@ -1,45 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_CONTACT_INFO_BOX2D_H__ -#define __CCPHYSICS_CONTACT_INFO_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#include "CCPlatformMacros.h" -NS_CC_BEGIN -class PhysicsContact; - -class PhysicsContactInfo -{ -public: - PhysicsContactInfo(PhysicsContact* contact); - ~PhysicsContactInfo(); -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_CONTACT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsHelper_box2d.h b/cocos/physics/box2d/CCPhysicsHelper_box2d.h deleted file mode 100644 index 8efa099a96..0000000000 --- a/cocos/physics/box2d/CCPhysicsHelper_box2d.h +++ /dev/null @@ -1,46 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_HELPER_BOX2D_H__ -#define __CCPHYSICS_HELPER_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "Box2D.h" -#include "CCPlatformMacros.h" -#include "CCGeometry.h" - -NS_CC_BEGIN - -class PhysicsHelper -{ -public: - static b2Vec2 point2Vec2(const Point& point) { return b2Vec2(point.x, point.y); } - static Point vec22Point(const b2Vec2& vec) { return Point(vec.x, vec.y); } -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_HELPER_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp deleted file mode 100644 index 27f4aaacbb..0000000000 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp +++ /dev/null @@ -1,41 +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 "CCPhysicsJointInfo_box2d.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPhysicsJoint.h" - -NS_CC_BEGIN - -PhysicsJointInfo::PhysicsJointInfo(PhysicsJoint* joint) -{ -} - -PhysicsJointInfo::~PhysicsJointInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h b/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h deleted file mode 100644 index 719126886a..0000000000 --- a/cocos/physics/box2d/CCPhysicsJointInfo_box2d.h +++ /dev/null @@ -1,46 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_JOINT_INFO_BOX2D_H__ -#define __CCPHYSICS_JOINT_INFO_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) - -#include "CCPlatformMacros.h" -NS_CC_BEGIN - -class PhysicsJoint; - -class PhysicsJointInfo -{ -public: - PhysicsJointInfo(PhysicsJoint* joint); - ~PhysicsJointInfo(); -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_JOINT_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp deleted file mode 100644 index 4fad8d15b5..0000000000 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp +++ /dev/null @@ -1,40 +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 "CCPhysicsShapeInfo_box2d.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPhysicsShape.h" -NS_CC_BEGIN - -PhysicsShapeInfo::PhysicsShapeInfo(PhysicsShape* shape) -{ -} - -PhysicsShapeInfo::~PhysicsShapeInfo() -{ -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h b/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h deleted file mode 100644 index bf3bcd4262..0000000000 --- a/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.h +++ /dev/null @@ -1,47 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_SHAPE_INFO_BOX2D_H__ -#define __CCPHYSICS_SHAPE_INFO_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPlatformMacros.h" -NS_CC_BEGIN -class PhysicsShape; - -class PhysicsShapeInfo -{ -public: - PhysicsShapeInfo(PhysicsShape* shape); - ~PhysicsShapeInfo(); - -public: - PhysicsShape* shape; -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_SHAPE_INFO_BOX2D_H__ diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp deleted file mode 100644 index 2215a27692..0000000000 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp +++ /dev/null @@ -1,89 +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 "CCPhysicsWorldInfo_box2d.h" - -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "CCPhysicsHelper_box2d.h" -#include "CCPhysicsBodyInfo_box2d.h" -#include "CCPhysicsShapeInfo_box2d.h" -#include "CCPhysicsJointInfo_box2d.h" -NS_CC_BEGIN - -PhysicsWorldInfo::PhysicsWorldInfo() -{ - _world = new b2World(b2Vec2(0.0f, 0.0f)); -} - -PhysicsWorldInfo::~PhysicsWorldInfo() -{ - CC_SAFE_DELETE(_world); -} - -void PhysicsWorldInfo::setGravity(const Vect& gravity) -{ - _world->SetGravity(PhysicsHelper::point2Vec2(gravity)); -} - -void PhysicsWorldInfo::addBody(PhysicsBodyInfo& body) -{ - if (body.getBody() != nullptr) - { - removeBody(body); - } - - body.setBody(_world->CreateBody(&body.getBodyDef())); -} - -void PhysicsWorldInfo::removeBody(PhysicsBodyInfo& body) -{ - if (body.getBody() != nullptr) - { - _world->DestroyBody(body.getBody()); - body.setBody(nullptr); - } -} - -void PhysicsWorldInfo::addShape(PhysicsShapeInfo& shape) -{ - -} - -void PhysicsWorldInfo::removeShape(PhysicsShapeInfo& shape) -{ - -} - -void PhysicsWorldInfo::addJoint(PhysicsJointInfo& joint) -{ - -} - -void PhysicsWorldInfo::removeJoint(PhysicsJointInfo& joint) -{ - -} - -NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D diff --git a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h b/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h deleted file mode 100644 index faf7da0132..0000000000 --- a/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.h +++ /dev/null @@ -1,66 +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. - ****************************************************************************/ - -#ifndef __CCPHYSICS_WORLD_INFO_BOX2D_H__ -#define __CCPHYSICS_WORLD_INFO_BOX2D_H__ - -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D) -#include "Box2D.h" -#include "CCPlatformMacros.h" -NS_CC_BEGIN -class PhysicsBodyInfo; -class PhysicsJointInfo; -class PhysicsShapeInfo; - -class PhysicsWorldInfo -{ -public: - inline b2World* getWorld() { return _world; } - void addShape(PhysicsShapeInfo& shape); - void removeShape(PhysicsShapeInfo& shape); - void addBody(PhysicsBodyInfo& body); - void removeBody(PhysicsBodyInfo& body); - void addJoint(PhysicsJointInfo& joint); - void removeJoint(PhysicsJointInfo& joint); - void setGravity(const Vect& gravity); - inline bool isLocked() { return _world->IsLocked(); } - inline void step(float delta) { _world->Step(delta, VELOCITY_ITERRATIONS, POSITION_ITERRATIONS); } - -private: - b2World* _world; - static const int32 VELOCITY_ITERRATIONS = 8; - static const int32 POSITION_ITERRATIONS = 1; - -private: - PhysicsWorldInfo(); - ~PhysicsWorldInfo(); - - friend class PhysicsWorld; -}; - -NS_CC_END - -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_BOX2D -#endif // __CCPHYSICS_WORLD_INFO_BOX2D_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp index 79ad011c17..6cda96c2e1 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ +#ifdef CC_USE_PHYSICS #include "CCPhysicsBodyInfo_chipmunk.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN PhysicsBodyInfo::PhysicsBodyInfo() @@ -37,4 +37,4 @@ PhysicsBodyInfo::~PhysicsBodyInfo() } NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index 143fec843c..40509df692 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -25,8 +25,7 @@ #ifndef __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ #define __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifdef CC_USE_PHYSICS #include "chipmunk.h" #include "CCPlatformMacros.h" @@ -52,5 +51,5 @@ private: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_BODY_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp index 150c77a030..e0e4cfd85a 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ +#ifdef CC_USE_PHYSICS #include "CCPhysicsContactInfo_chipmunk.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) NS_CC_BEGIN PhysicsContactInfo::PhysicsContactInfo(PhysicsContact* contact) @@ -36,4 +36,4 @@ PhysicsContactInfo::~PhysicsContactInfo() } NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h index 6cc0e189c1..1ba81dbba7 100644 --- a/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.h @@ -25,8 +25,7 @@ #ifndef __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ #define __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifdef CC_USE_PHYSICS #include "chipmunk.h" #include "CCPlatformMacros.h" @@ -50,5 +49,5 @@ private: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_CONTACT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h index 1b4c6ac82d..7641a78cfa 100644 --- a/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsHelper_chipmunk.h @@ -25,8 +25,7 @@ #ifndef __CCPHYSICS_HELPER_CHIPMUNK_H__ #define __CCPHYSICS_HELPER_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifdef CC_USE_PHYSICS #include "chipmunk.h" #include "CCPlatformMacros.h" @@ -69,5 +68,5 @@ public: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_HELPER_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp index 2f8b7817cf..af8da99fb9 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ +#ifdef CC_USE_PHYSICS #include "CCPhysicsJointInfo_chipmunk.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN @@ -79,4 +79,4 @@ void PhysicsJointInfo::removeAll() } NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h index bdd3f1e887..8b91842941 100644 --- a/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.h @@ -25,8 +25,7 @@ #ifndef __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ #define __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifdef CC_USE_PHYSICS #include "chipmunk.h" #include "CCPlatformMacros.h" @@ -61,5 +60,5 @@ private: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_JOINT_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp index d12a053181..2dd133d37a 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ +#ifdef CC_USE_PHYSICS #include "CCPhysicsShapeInfo_chipmunk.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include NS_CC_BEGIN @@ -113,4 +113,4 @@ void PhysicsShapeInfo::removeAll() } NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h index 2bdd55a7f9..56301b5f25 100644 --- a/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.h @@ -25,8 +25,7 @@ #ifndef __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ #define __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#if CC_USE_PHYSICS #include #include @@ -71,5 +70,5 @@ private: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_SHAPE_INFO_CHIPMUNK_H__ diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index 2f9ba4db18..56478d4ac9 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -22,8 +22,9 @@ THE SOFTWARE. ****************************************************************************/ +#ifdef CC_USE_PHYSICS +#include "ccConfig.h" #include "CCPhysicsWorldInfo_chipmunk.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) #include "CCPhysicsHelper_chipmunk.h" #include "CCPhysicsBodyInfo_chipmunk.h" #include "CCPhysicsShapeInfo_chipmunk.h" @@ -97,4 +98,4 @@ void PhysicsWorldInfo::removeJoint(PhysicsJointInfo& joint) } NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 3e4ce9a965..85f45c1732 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -25,14 +25,14 @@ #ifndef __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ #define __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ -#include "../CCPhysicsSetting.h" -#if (CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK) +#ifdef CC_USE_PHYSICS #include #include "chipmunk.h" #include "CCPlatformMacros.h" #include "CCGeometry.h" NS_CC_BEGIN +class Vect; class PhysicsBodyInfo; class PhysicsJointInfo; class PhysicsShapeInfo; @@ -63,5 +63,5 @@ private: NS_CC_END -#endif // CC_PHYSICS_ENGINE == CC_PHYSICS_CHIPMUNK +#endif // CC_USE_PHYSICS #endif // __CCPHYSICS_WORLD_INFO_CHIPMUNK_H__ diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index 89197f3fec..dc84cc0540 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -91,7 +91,7 @@ void PhysicsTestScene::toggleDebug() #ifndef CC_USE_PHYSICS void PhysicsDemoDisabled::onEnter() { - auto label = LabelTTF::create("Should define CC_USE_BOX2D or CC_USE_CHIPMUNK\n to run this test case", + auto label = LabelTTF::create("Should define CC_USE_PHYSICS\n to run this test case", "Arial", 18); auto size = Director::getInstance()->getWinSize(); From 6f67447b5e151dd8cc4c2e6d97155cf68b8beb03 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 15:43:39 +0800 Subject: [PATCH 40/75] =?UTF-8?q?issue=20#3258:=20Updates=20cocos2dx.ini.?= =?UTF-8?q?=20Adding=20some=20classes=20to=20=E2=80=98classes=5Fneed=5Fext?= =?UTF-8?q?end=E2=80=99=20section.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/tojs/cocos2dx.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index 2acfad1a34..bd3f409288 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -28,6 +28,8 @@ headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/Simpl # expression, it will be enclosed in "^$", like this: "^Menu*$". classes = Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set Data SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak TextFieldTTF EGLViewProtocol EGLView Component +classes_need_extend = Node Layer.* Sprite MenuItemFont Scene DrawNode + # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also # regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just From b55e8f17c71d51179602c4cbaba29509cab327fb Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 15:44:21 +0800 Subject: [PATCH 41/75] issue #3258: MenuItemFont has empty argument create function now. --- cocos/2d/CCMenuItem.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index fb44773d27..09de7fe399 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -246,7 +246,7 @@ class CC_DLL MenuItemFont : public MenuItemLabel { public: /** creates a menu item from a string without target/selector. To be used with MenuItemToggle */ - static MenuItemFont * create(const std::string& value); + static MenuItemFont * create(const std::string& value = ""); /** creates a menu item from a string with a target/selector */ CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); /** creates a menu item from a string with a target/selector */ From ebcdf2f87d62295105fd5ec27e3b7177516aea36 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 15:44:49 +0800 Subject: [PATCH 42/75] issue #3258: Bug fix of MenuItemToggle binding. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index f72dd9cbdf..0fca450a63 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -e25d022404007994fb9abd210bd35646a217e49e \ No newline at end of file +779c204bb8fdea3bbe3fe7ac2f687b1d0250ee3a \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index c3dcf3390c..0f09dcedde 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -86fa141032de3d513df690fc82b20d2f2b4ab01b \ No newline at end of file +270dc280a6f338f52b0147dc00421c5478941304 \ No newline at end of file From 03005173b1d26e9ad3882c2188ce134201aeb5f9 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 15:45:09 +0800 Subject: [PATCH 43/75] issue #3258: Updates bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index 2f3c19e01d..e6c7016f83 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 2f3c19e01d5043485d0887ad69a3f02e312ad690 +Subproject commit e6c7016f83c9d02e0b8e784c65043369a1745680 From 63702188be4f7fbd90af05edfef87f8de9ea66b3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 15:56:43 +0800 Subject: [PATCH 44/75] issue #3258: Compilation error fix for linux port. --- cocos/2d/platform/linux/CCEGLView.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 612f936d51..d8fbbf5737 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -290,7 +290,7 @@ EGLView::EGLView() { CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); s_pEglView = this; - strcpy(_viewName, "Cocos2dxWin32"); + _viewName = "Cocos2dxWin32"; glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); glfwInit(); } @@ -310,7 +310,7 @@ bool EGLView::init(const char* viewName, float width, float height, float frameZ setFrameZoomFactor(frameZoomFactor); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName, nullptr, nullptr); + _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); glfwMakeContextCurrent(_mainWindow); glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); From a04c45f0d9c17c18ed89cebe2a78a649db0739e5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 16:19:12 +0800 Subject: [PATCH 45/75] issue #3258: Renames ControlSwitchSprite::createWithMaskSprite to ControlSwitchSprite::create. --- extensions/GUI/CCControlExtension/CCControlSwitch.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index 8a7d046593..13b2329579 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -35,7 +35,7 @@ class ControlSwitchSprite : public Sprite, public ActionTweenDelegate { public: /** creates an autorelease instance of ControlSwitchSprite */ - static ControlSwitchSprite* createWithMaskSprite( + static ControlSwitchSprite* create( Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, @@ -121,7 +121,7 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(ControlSwitchSprite); }; -ControlSwitchSprite* ControlSwitchSprite::createWithMaskSprite(Sprite *maskSprite, +ControlSwitchSprite* ControlSwitchSprite::create(Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, @@ -376,7 +376,7 @@ bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sp _on = true; - _switchSprite = ControlSwitchSprite::createWithMaskSprite(maskSprite, + _switchSprite = ControlSwitchSprite::create(maskSprite, onSprite, offSprite, thumbSprite, From 17c4631f45f1ba2416a9d117f66a0b0762e8c363 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Tue, 26 Nov 2013 08:36:22 +0000 Subject: [PATCH 46/75] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 4920a65f2f..86ee6e4468 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 4920a65f2fd68f694584f220fe8065931561224a +Subproject commit 86ee6e4468b81db04dcdc286392fec41e9ec33a7 From d650c0a6a1fb4ebc1935e8d4d96cc56bd50fc314 Mon Sep 17 00:00:00 2001 From: hanson Date: Tue, 26 Nov 2013 17:03:01 +0800 Subject: [PATCH 47/75] add gui namespace before SEL_TouchEvent --- cocos/gui/UIWidget.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index 065f794721..84852df00e 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -71,7 +71,7 @@ typedef enum }PositionType; typedef void (cocos2d::Object::*SEL_TouchEvent)(cocos2d::Object*,TouchEventType); -#define toucheventselector(_SELECTOR) (SEL_TouchEvent)(&_SELECTOR) +#define toucheventselector(_SELECTOR) (gui::SEL_TouchEvent)(&_SELECTOR) class UIWidget : public cocos2d::Object { From 0100c05a933f9b0280ebb2a54f8ece45acb1a108 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 26 Nov 2013 17:29:09 +0800 Subject: [PATCH 48/75] issue #2771: fix compile errors --- cocos/2d/ccConfig.h | 5 ----- cocos/physics/CCPhysicsBody.h | 3 ++- cocos/physics/CCPhysicsContact.h | 1 + cocos/physics/CCPhysicsWorld.h | 2 ++ cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/cocos/2d/ccConfig.h b/cocos/2d/ccConfig.h index 5cf5af7bdc..b8729d0d28 100644 --- a/cocos/2d/ccConfig.h +++ b/cocos/2d/ccConfig.h @@ -268,11 +268,6 @@ To enable set it to a value different than 0. Disabled by default. #ifdef CC_USE_PHYSICS #define PHYSICS_CONTACT_POINT_MAX 4 -namespace cocos2d -{ - class Point; - typedef Point Vect; -} #endif #endif // __CCCONFIG_H__ diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 731af4bbd0..ebff4c777f 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -40,9 +40,10 @@ NS_CC_BEGIN class Sprite; class PhysicsWorld; class PhysicsJoint; - class PhysicsBodyInfo; +typedef Point Vect; + const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 40d9081653..d9655754f0 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -40,6 +40,7 @@ class PhysicsWorld; class PhysicsContactInfo; +typedef Point Vect; typedef struct PhysicsContactData { diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 71f977c5f4..2b9f34d140 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -42,6 +42,8 @@ class PhysicsShape; class PhysicsContact; class Array; +typedef Point Vect; + class Sprite; class Scene; class DrawNode; diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h index 85f45c1732..7eda879ec9 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.h @@ -32,7 +32,7 @@ #include "CCPlatformMacros.h" #include "CCGeometry.h" NS_CC_BEGIN -class Vect; +typedef Point Vect; class PhysicsBodyInfo; class PhysicsJointInfo; class PhysicsShapeInfo; From 888fd73702eb0b7430d259389b2e94440da779aa Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 17:44:24 +0800 Subject: [PATCH 49/75] Update AUTHORS --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index dfa56dbe1e..98a6d05ea4 100644 --- a/AUTHORS +++ b/AUTHORS @@ -662,6 +662,9 @@ Developers: lajos FontTest isn't rendered correctly with custom TTF font on Mac platform. + hulefei + Added gui namespace before SEL_TouchEvent. + Retired Core Developers: WenSheng Yang Author of windows port, CCTextField, From ba101809dea05cc6f64553a763ea612a850435bf Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 26 Nov 2013 17:49:50 +0800 Subject: [PATCH 50/75] [ci skip] --- CHANGELOG | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index e8c396b192..23a4a71c45 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +cocos2d-x-3.0beta0 ?? 2013 +[Android] + [NEW] build/android-build.sh: add supporting to generate .apk file + cocos2d-x-3.0alpha1 Nov.19 2013 [all platforms] [DOC] Added RELEASE_NOTES and CODING_STYLE.md files From fcf43823b476c4a42b26ff0d145e5ebfee6e3b2b Mon Sep 17 00:00:00 2001 From: minggo Date: Tue, 26 Nov 2013 16:52:00 +0800 Subject: [PATCH 51/75] remove unneeded codes --- cocos/2d/CCSprite.cpp | 37 ------------------------------------- cocos/2d/CCSprite.h | 3 +-- 2 files changed, 1 insertion(+), 39 deletions(-) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 7fb20d95df..cc123e3a5d 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -267,32 +267,6 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) } } -// 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 = Director::getInstance()->getTextureCache()->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) @@ -685,16 +659,6 @@ void Sprite::draw(void) // 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"); @@ -744,7 +708,6 @@ void Sprite::removeChild(Node *child, bool cleanup) } Node::removeChild(child, cleanup); - } void Sprite::removeAllChildrenWithCleanup(bool cleanup) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 878ef94e51..f9d8d768f9 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -412,8 +412,7 @@ public: virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void reorderChild(Node *child, int zOrder) override; - virtual void addChild(Node *child) override; - virtual void addChild(Node *child, int zOrder) override; + using Node::addChild; virtual void addChild(Node *child, int zOrder, int tag) override; virtual void sortAllChildren() override; virtual void setScale(float scale) override; From 8346fe4b4db247486d657d8dd03979257d94ce13 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Tue, 26 Nov 2013 18:22:52 +0800 Subject: [PATCH 52/75] issue #2771: edit android.mk, CMakeLists.txt, change PHYSICS_CONTACT_POINT_MAX to PhysicsContactData:POINT_MAX --- cocos/2d/Android.mk | 9 ++------- cocos/2d/ccConfig.h | 4 ---- cocos/physics/CCPhysicsContact.cpp | 2 +- cocos/physics/CCPhysicsContact.h | 3 ++- cocos/physics/CMakeLists.txt | 5 ----- 5 files changed, 5 insertions(+), 18 deletions(-) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 6d36b83b55..854d56829d 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -39,13 +39,13 @@ CCEventAcceleration.cpp \ CCEventCustom.cpp \ CCEventDispatcher.cpp \ CCEventKeyboard.cpp \ -CCEventMouse.cpp \ -CCEventListenerMouse.cpp \ CCEventListener.cpp \ CCEventListenerAcceleration.cpp \ CCEventListenerCustom.cpp \ CCEventListenerKeyboard.cpp \ +CCEventListenerMouse.cpp \ CCEventListenerTouch.cpp \ +CCEventMouse.cpp \ CCEventTouch.cpp \ CCFont.cpp \ CCFontAtlas.cpp \ @@ -149,11 +149,6 @@ platform/CCThread.cpp \ ../physics/CCPhysicsJoint.cpp \ ../physics/CCPhysicsShape.cpp \ ../physics/CCPhysicsWorld.cpp \ -../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \ -../physics/box2d/CCPhysicsContactInfo_box2d.cpp \ -../physics/box2d/CCPhysicsJointInfo_box2d.cpp \ -../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \ -../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \ ../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \ ../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \ ../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \ diff --git a/cocos/2d/ccConfig.h b/cocos/2d/ccConfig.h index b8729d0d28..f801066bfe 100644 --- a/cocos/2d/ccConfig.h +++ b/cocos/2d/ccConfig.h @@ -266,8 +266,4 @@ To enable set it to a value different than 0. Disabled by default. #define CC_LUA_ENGINE_DEBUG 0 #endif -#ifdef CC_USE_PHYSICS -#define PHYSICS_CONTACT_POINT_MAX 4 -#endif - #endif // __CCCONFIG_H__ diff --git a/cocos/physics/CCPhysicsContact.cpp b/cocos/physics/CCPhysicsContact.cpp index e0233df958..649d0756f4 100644 --- a/cocos/physics/CCPhysicsContact.cpp +++ b/cocos/physics/CCPhysicsContact.cpp @@ -98,7 +98,7 @@ void PhysicsContact::generateContactData() cpArbiter* arb = static_cast(_contactInfo); _contactData = new PhysicsContactData(); _contactData->count = cpArbiterGetCount(arb); - for (int i=0; i<_contactData->count; ++i) + for (int i=0; i<_contactData->count && ipoints[i] = PhysicsHelper::cpv2point(cpArbiterGetPoint(arb, i)); } diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index d9655754f0..24eb0f4c69 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -44,7 +44,8 @@ typedef Point Vect; typedef struct PhysicsContactData { - Point points[PHYSICS_CONTACT_POINT_MAX]; + static const long POINT_MAX = 4; + Point points[POINT_MAX]; int count; Point normal; diff --git a/cocos/physics/CMakeLists.txt b/cocos/physics/CMakeLists.txt index 1586db2379..ef81f5ec6b 100644 --- a/cocos/physics/CMakeLists.txt +++ b/cocos/physics/CMakeLists.txt @@ -1,9 +1,4 @@ set(COCOS_PHYSICS_SRC - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsContactInfo_box2d.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsJointInfo_box2d.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsShapeInfo_box2d.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsBodyInfo_box2d.cpp - ${CMAKE_SOURCE_DIR}/cocos/physics/box2d/CCPhysicsWorldInfo_box2d.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp ${CMAKE_SOURCE_DIR}/cocos/physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp From ecc7783685bf24246ed6d24cfc195abe4873329c Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 20:31:44 +0800 Subject: [PATCH 53/75] closed #3279: XMLHttpRequest receives wrong binary array. --- .../bindings/network/XMLHTTPRequest.cpp | 23 +++++++++++-------- .../bindings/network/XMLHTTPRequest.h | 2 +- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index e3524aba36..71657fe7e5 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -200,18 +200,18 @@ void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, netw /** get the response data **/ std::vector *buffer = response->getResponseData(); - char* concatenated = (char*) malloc(buffer->size() + 1); - std::string s2(buffer->begin(), buffer->end()); - - strcpy(concatenated, s2.c_str()); if (statusCode == 200) { //Succeeded _status = 200; _readyState = DONE; - _data << concatenated; + _dataSize = buffer->size(); + CC_SAFE_FREE(_data); + _data = (char*) malloc(_dataSize + 1); + _data[_dataSize] = '\0'; + memcpy((void*)_data, (const void*)buffer->data(), _dataSize); } else { @@ -219,7 +219,6 @@ void MinXmlHttpRequest::handle_requestResponse(network::HttpClient *sender, netw } // Free Memory. free((void*) concatHeader); - free((void*) concatenated); js_proxy_t * p; void* ptr = (void*)this; @@ -256,7 +255,10 @@ void MinXmlHttpRequest::_sendRequest(JSContext *cx) * @brief Constructor initializes cchttprequest and stuff * */ -MinXmlHttpRequest::MinXmlHttpRequest() : _onreadystateCallback(NULL), _isNetwork(true) +MinXmlHttpRequest::MinXmlHttpRequest() +: _onreadystateCallback(nullptr) +, _isNetwork(true) +, _data(nullptr) { _httpHeader.clear(); _requestHeader.clear(); @@ -285,6 +287,7 @@ MinXmlHttpRequest::~MinXmlHttpRequest() // _httpRequest->release(); } + CC_SAFE_FREE(_data); } /** @@ -543,7 +546,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) */ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) { - jsval strVal = std_string_to_jsval(cx, _data.str()); + jsval strVal = std_string_to_jsval(cx, _data); if (strVal != JSVAL_NULL) { @@ -567,7 +570,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) { JS::RootedValue outVal(cx); - jsval strVal = std_string_to_jsval(cx, _data.str()); + jsval strVal = std_string_to_jsval(cx, _data); if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) { vp.set(outVal); @@ -578,7 +581,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) { JSObject* tmp = JS_NewArrayBuffer(cx, _dataSize); uint8_t* tmpData = JS_GetArrayBufferData(tmp); - _data.read((char*)tmpData, _dataSize); + memcpy((void*)tmpData, (const void*)_data, _dataSize); jsval outVal = OBJECT_TO_JSVAL(tmp); vp.set(outVal); diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h index 7a4be6b822..769e9054b8 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -93,7 +93,7 @@ private: JSContext* _cx; std::string _meth; std::string _type; - std::stringstream _data; + char* _data; size_t _dataSize; JSObject* _onreadystateCallback; int _readyState; From f6a1f5cc951954ac5ea410189b2c4b401ae0093e Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 26 Nov 2013 21:54:48 +0800 Subject: [PATCH 54/75] issue #3279: A warning fix for 64bit platform. --- cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h index 769e9054b8..e5e26c41b1 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -94,7 +94,7 @@ private: std::string _meth; std::string _type; char* _data; - size_t _dataSize; + uint32_t _dataSize; JSObject* _onreadystateCallback; int _readyState; int _status; From b7f7b0dae438837bafffe3dc7d4569790476560f Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 26 Nov 2013 14:36:31 -0800 Subject: [PATCH 55/75] Reports wether the build is DEBUG or RELEASE Reports wether the build is DEBUG or RELEASE in Configuration --- cocos/2d/CCConfiguration.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index 48b4156ca5..9aa44b5295 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -78,6 +78,12 @@ bool Configuration::init() _valueDict->setObject(Bool::create(true), "cocos2d.x.compiled_with_gl_state_cache"); #endif +#ifdef DEBUG + _valueDict->setObject(String::create("DEBUG"), "cocos2d.x.build_type"); +#else + _valueDict->setObject(String::create("RELEASE"), "cocos2d.x.build_type"); +#endif + return true; } From 85002285c20d4f4882fb459aaafdbce401c5a506 Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 27 Nov 2013 09:50:47 +0800 Subject: [PATCH 56/75] override addChild in Sprite to fix error in binding generator --- cocos/2d/CCSprite.cpp | 10 ++++++++++ cocos/2d/CCSprite.h | 8 ++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index cc123e3a5d..b4be678d87 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -659,6 +659,16 @@ void Sprite::draw(void) // 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"); diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index f9d8d768f9..c249f427b7 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -78,9 +78,6 @@ struct transformValues_; * The default anchorPoint in Sprite is (0.5, 0.5). */ class CC_DLL Sprite : public NodeRGBA, public TextureProtocol -#ifdef EMSCRIPTEN -, public GLBufferedNode -#endif // EMSCRIPTEN { public: @@ -412,7 +409,10 @@ public: virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void reorderChild(Node *child, int zOrder) override; - using Node::addChild; + // Shoul also override addChild(Node*) and addChild(Node*, int), or binding generator will only + // bind addChild(Node*, int, int); + virtual void addChild(Node* child) override; + virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node *child, int zOrder, int tag) override; virtual void sortAllChildren() override; virtual void setScale(float scale) override; From 0ac90222017659775f747fdb4d773642009cc06b Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 27 Nov 2013 10:02:32 +0800 Subject: [PATCH 57/75] fix a typo --- cocos/2d/CCSprite.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index c249f427b7..a78a120589 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -409,7 +409,7 @@ public: virtual void removeChild(Node* child, bool cleanup) override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; virtual void reorderChild(Node *child, int zOrder) override; - // Shoul also override addChild(Node*) and addChild(Node*, int), or binding generator will only + // Should also override addChild(Node*) and addChild(Node*, int), or binding generator will only // bind addChild(Node*, int, int); virtual void addChild(Node* child) override; virtual void addChild(Node* child, int zOrder) override; From dda13b7e8a8a2f1174dea3aad89f9cf590193804 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 27 Nov 2013 02:18:42 +0000 Subject: [PATCH 58/75] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 86ee6e4468..75427a6325 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 86ee6e4468b81db04dcdc286392fec41e9ec33a7 +Subproject commit 75427a63259b1029ea9e000727c65f14cd389e91 From 3469f2adf5573d97a97462a9f9cf4e25d06d0a4a Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 27 Nov 2013 10:34:05 +0800 Subject: [PATCH 59/75] closed #2539:use unstripped libcurl lib for armeabi-v7 architecture to fix link warnings --- .../curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id index 2b1b61860f..441201cceb 100644 --- a/external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id +++ b/external/curl/prebuilt/android/armeabi-v7a/libcurl.a.REMOVED.git-id @@ -1 +1 @@ -44e542ea244df0150ae90190bf59a34356ac2c25 \ No newline at end of file +0121559669b9a084d0677116b0cfa09c617b4cd7 \ No newline at end of file From 94c41ea51edca943c1b32f58aba0bb1390786375 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 11:03:16 +0800 Subject: [PATCH 60/75] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 23a4a71c45..a6e23ff12a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ cocos2d-x-3.0beta0 ?? 2013 [Android] [NEW] build/android-build.sh: add supporting to generate .apk file + [FIX] XMLHttpRequest receives wrong binary array. cocos2d-x-3.0alpha1 Nov.19 2013 [all platforms] From 4311e7c469858066b056cdd31b935fd17b766ae3 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 13:52:41 +0800 Subject: [PATCH 61/75] =?UTF-8?q?[Script=20Binding]=20Bind=20=E2=80=98unsi?= =?UTF-8?q?gned=20long=E2=80=99.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bindings/js_manual_conversions.cpp | 90 +++++++++++++------ .../bindings/js_manual_conversions.h | 27 +++--- .../lua/bindings/LuaBasicConversions.cpp | 24 +++++ 3 files changed, 99 insertions(+), 42 deletions(-) diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 411ce359ec..26c5a14009 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -93,34 +93,6 @@ JSBool jsval_to_int( JSContext *cx, jsval vp, int *ret ) return jsval_to_int32(cx, vp, (int32_t*)ret); } -// XXX: sizeof(long) == 8 in 64 bits on OS X... apparently on Windows it is 32 bits (???) -JSBool jsval_to_long( JSContext *cx, jsval vp, long *r ) -{ -#ifdef __LP64__ - // compatibility check - assert( sizeof(long)==8); - JSString *jsstr = JS_ValueToString(cx, vp); - JSB_PRECONDITION2(jsstr, cx, JS_FALSE, "Error converting value to string"); - - char *str = JS_EncodeString(cx, jsstr); - JSB_PRECONDITION2(str, cx, JS_FALSE, "Error encoding string"); - - char *endptr; - long ret = strtol(str, &endptr, 10); - - *r = ret; - return JS_TRUE; - -#else - // compatibility check - assert( sizeof(int)==4); - long ret = JSVAL_TO_INT(vp); -#endif - - *r = ret; - return JS_TRUE; -} - jsval opaque_to_jsval( JSContext *cx, void *opaque ) { #ifdef __LP64__ @@ -191,6 +163,21 @@ jsval long_to_jsval( JSContext *cx, long number ) #endif } +jsval ulong_to_jsval( JSContext *cx, unsigned long number ) +{ +#ifdef __LP64__ + assert( sizeof(unsigned long)==8); + + char chr[128]; + snprintf(chr, sizeof(chr)-1, "%lu", number); + JSString *ret_obj = JS_NewStringCopyZ(cx, chr); + return STRING_TO_JSVAL(ret_obj); +#else + CCASSERT( sizeof(int)==4, "Error!"); + return UINT_TO_JSVAL(number); +#endif +} + jsval longlong_to_jsval( JSContext *cx, long long number ) { #if JSB_REPRESENT_LONGLONG_AS_STR @@ -367,7 +354,52 @@ JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) return ok; } -JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { +// XXX: sizeof(long) == 8 in 64 bits on OS X... apparently on Windows it is 32 bits (???) +JSBool jsval_to_long( JSContext *cx, jsval vp, long *r ) +{ +#ifdef __LP64__ + // compatibility check + assert( sizeof(long)==8); + JSString *jsstr = JS_ValueToString(cx, vp); + JSB_PRECONDITION2(jsstr, cx, JS_FALSE, "Error converting value to string"); + + char *str = JS_EncodeString(cx, jsstr); + JSB_PRECONDITION2(str, cx, JS_FALSE, "Error encoding string"); + + char *endptr; + long ret = strtol(str, &endptr, 10); + + *r = ret; + return JS_TRUE; + +#else + // compatibility check + assert( sizeof(int)==4); + long ret = JSVAL_TO_INT(vp); +#endif + + *r = ret; + return JS_TRUE; +} + + +JSBool jsval_to_ulong( JSContext *cx, jsval vp, unsigned long *out) +{ + if (out == nullptr) + return JS_FALSE; + + long rval = 0; + JSBool ret = JS_FALSE; + ret = jsval_to_long(cx, vp, &rval); + if (ret) + { + *out = (unsigned long)rval; + } + return ret; +} + +JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) +{ JSObject *tmp_arg; JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index b3d15c86e1..b0a8e80684 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -9,29 +9,28 @@ #include "js_bindings_core.h" #include "cocos2d.h" -extern JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); -extern JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); -extern JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); -extern JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); -extern JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); +JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); +JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); +JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); +JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); /** converts a jsval (JS string) into a char */ -extern JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); +JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); -extern jsval opaque_to_jsval( JSContext *cx, void* opaque); -extern jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); -extern jsval long_to_jsval( JSContext *cx, long number ); -extern jsval longlong_to_jsval( JSContext *cx, long long number ); +jsval opaque_to_jsval( JSContext *cx, void* opaque); +jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); /* Converts a char ptr into a jsval (using JS string) */ -extern jsval charptr_to_jsval( JSContext *cx, const char *str); -extern JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); -extern JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); +jsval charptr_to_jsval( JSContext *cx, const char *str); +JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); +JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); // some utility functions // to native JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); +JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); +JSBool jsval_to_ulong( JSContext *cx, jsval vp, unsigned long *out); JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); JSBool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); @@ -51,6 +50,8 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition // from native jsval int32_to_jsval( JSContext *cx, int32_t l); jsval uint32_to_jsval( JSContext *cx, uint32_t number ); +jsval long_to_jsval( JSContext *cx, long number ); +jsval ulong_to_jsval(JSContext* cx, unsigned long v); jsval long_long_to_jsval(JSContext* cx, long long v); jsval std_string_to_jsval(JSContext* cx, const std::string& v); jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length = -1); diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index ef080cb288..b3b99b4e40 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -307,6 +307,30 @@ bool luaval_to_long(lua_State* L,int lo, long* outValue) return ok; } +bool luaval_to_ulong(lua_State* L,int lo, unsigned long* outValue) +{ + if (NULL == L || NULL == outValue) + return false; + + bool ok = true; + + tolua_Error tolua_err; + if (!tolua_isnumber(L,lo,0,&tolua_err)) + { +#if COCOS2D_DEBUG >=1 + luaval_to_native_err(L,"#ferror:",&tolua_err); +#endif + ok = false; + } + + if (ok) + { + *outValue = (unsigned long)tolua_tonumber(L, lo, 0); + } + + return ok; +} + bool luaval_to_size(lua_State* L,int lo,Size* outValue) { if (NULL == L || NULL == outValue) From 216f8743b0584038be74bce217f4a5b642a4ddc7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 14:04:53 +0800 Subject: [PATCH 62/75] closed #3288: Updates bindings-generator. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index e6c7016f83..3e215fc486 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit e6c7016f83c9d02e0b8e784c65043369a1745680 +Subproject commit 3e215fc4865a75e25db6f45115350ef2d7a256ca From 6dc9183c8a4ad779cdf8a54a30b21feb58617ac7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 14:12:43 +0800 Subject: [PATCH 63/75] closed #3289: [JSB] 'Test Frame Event' of CocoStudioArmatureTest Crashes! --- .../bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index 56f7d926e1..ae8ffb323d 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -102,6 +102,8 @@ void JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc(float percent) void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *frameEventName, int originFrameIndex, int currentFrameIndex) { + JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject *thisObj = JSVAL_IS_VOID(_jsThisObj) ? NULL : JSVAL_TO_OBJECT(_jsThisObj); js_proxy_t *proxy = js_get_or_create_proxy(cx, pBone); @@ -120,8 +122,6 @@ void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *pBone, const char *f JS_AddValueRoot(cx, valArr); - JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET - JS_CallFunctionValue(cx, thisObj, _jsCallback, 4, valArr, &retval); JS_RemoveValueRoot(cx, valArr); } From c63698b488d092c55472470507e8c9b9b724e97c Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 14:23:24 +0800 Subject: [PATCH 64/75] Update CHANGELOG [ci skip] --- CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index a6e23ff12a..b3c129eb4e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,7 +2,7 @@ cocos2d-x-3.0beta0 ?? 2013 [Android] [NEW] build/android-build.sh: add supporting to generate .apk file [FIX] XMLHttpRequest receives wrong binary array. - + [NEW] Bindings-generator supports to bind 'unsigned long'. cocos2d-x-3.0alpha1 Nov.19 2013 [all platforms] [DOC] Added RELEASE_NOTES and CODING_STYLE.md files From 4d327b8180e8215e40f22e2c243942204cb628d9 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 27 Nov 2013 06:25:08 +0000 Subject: [PATCH 65/75] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 75427a6325..3f5c6fd908 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 75427a63259b1029ea9e000727c65f14cd389e91 +Subproject commit 3f5c6fd9082864d9dc214ce225e1515df279406d From 749fc5d95ba1096428a73562eb9f2e0301a270ba Mon Sep 17 00:00:00 2001 From: James Chen Date: Wed, 27 Nov 2013 14:31:05 +0800 Subject: [PATCH 66/75] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index b3c129eb4e..8a5ecb030f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ cocos2d-x-3.0beta0 ?? 2013 [NEW] build/android-build.sh: add supporting to generate .apk file [FIX] XMLHttpRequest receives wrong binary array. [NEW] Bindings-generator supports to bind 'unsigned long'. + [FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes. cocos2d-x-3.0alpha1 Nov.19 2013 [all platforms] [DOC] Added RELEASE_NOTES and CODING_STYLE.md files From bcb131262c3ad8872612c07fccd515c13b92374d Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 27 Nov 2013 16:49:07 +0800 Subject: [PATCH 67/75] add helper funcion to invoke a function in gl thread --- cocos/2d/CCDirector.cpp | 6 +- cocos/2d/CCTextureCache.cpp | 7 ++- cocos/2d/platform/CCThread.cpp | 55 ++++++++++++++++--- cocos/2d/platform/CCThread.h | 38 ++++++++++--- cocos/2d/platform/apple/CCThread.mm | 49 +++++++++++++++-- .../cocostudio/CCDataReaderHelper.cpp | 5 +- 6 files changed, 132 insertions(+), 28 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 7e90fe92d8..36f72c81c5 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -1026,9 +1026,6 @@ void DisplayLinkDirector::startAnimation() } _invalid = false; -#ifndef EMSCRIPTEN - Application::getInstance()->setAnimationInterval(_animationInterval); -#endif // EMSCRIPTEN } void DisplayLinkDirector::mainLoop() @@ -1040,6 +1037,9 @@ void DisplayLinkDirector::mainLoop() } else if (! _invalid) { + // invoke call back from other thread + ThreadHelper::doCallback(); + drawScene(); // release the objects diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 15b30ccb6a..6f4c521d3a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -163,9 +163,8 @@ void TextureCache::loadImage() while (true) { // create autorelease pool for iOS - Thread thread; - thread.createAutoreleasePool(); - + auto autolreasePool = ThreadHelper::createAutoreleasePool(); + std::queue *pQueue = _asyncStructQueue; _asyncStructQueueMutex.lock(); if (pQueue->empty()) @@ -207,6 +206,8 @@ void TextureCache::loadImage() _imageInfoMutex.lock(); _imageInfoQueue->push(imageInfo); _imageInfoMutex.unlock(); + + ThreadHelper::releaseAutoreleasePool(autolreasePool); } if(_asyncStructQueue != nullptr) diff --git a/cocos/2d/platform/CCThread.cpp b/cocos/2d/platform/CCThread.cpp index d3f5b15999..7d4a23a216 100644 --- a/cocos/2d/platform/CCThread.cpp +++ b/cocos/2d/platform/CCThread.cpp @@ -24,23 +24,62 @@ THE SOFTWARE. #include "CCThread.h" +NS_CC_BEGIN + // iOS and Mac already has a Thread.mm #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_MAC) -NS_CC_BEGIN +std::list>* ThreadHelper::_callbackList = new std::list>(); +std::mutex* ThreadHelper::_mutex = new std::mutex; +long ThreadHelper::_callbackNumberPerFrame = 5; -Thread::~Thread() + +void* ThreadHelper::createAutoreleasePool() { - // To prevent warning: private field '_autoreasePool' is not - // used [-Wunused-private-field] by CLANG. - _autoReleasePool = nullptr; + return nullptr; } -void Thread::createAutoreleasePool() +void ThreadHelper::releaseAutoreleasePool(void* autoreleasePool) { - + } -NS_CC_END +void ThreadHelper::runOnGLThread(std::function f) +{ + // Insert call back function + _mutex->lock(); + _callbackList->push_back(f); + _mutex->unlock(); +} + +void ThreadHelper::doCallback() +{ + _mutex->lock(); + auto iter = _callbackList->begin(); + long i = 0; + while (iter != _callbackList->end()) + { + auto f = *iter; + f(); + + ++i; + if (i >= _callbackNumberPerFrame) + { + break; + } + else + { + iter = _callbackList->erase(iter); + } + } + _mutex->unlock(); +} + +void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) +{ + _callbackNumberPerFrame = callbackNumberPerFrame; +} #endif + +NS_CC_END diff --git a/cocos/2d/platform/CCThread.h b/cocos/2d/platform/CCThread.h index 46936642eb..b0998eeb59 100644 --- a/cocos/2d/platform/CCThread.h +++ b/cocos/2d/platform/CCThread.h @@ -25,8 +25,12 @@ THE SOFTWARE. #ifndef __CC_PLATFORM_THREAD_H__ #define __CC_PLATFORM_THREAD_H__ +#include +#include +#include #include "platform/CCCommon.h" #include "CCPlatformMacros.h" +#include "CCDirector.h" NS_CC_BEGIN @@ -39,27 +43,45 @@ NS_CC_BEGIN * and release it when the thread end. */ -class CC_DLL Thread +class CC_DLL ThreadHelper { public: - /** + friend DisplayLinkDirector; + + /** Create an autorelease pool for objective-c codes. * @js NA * @lua NA */ - Thread() : _autoReleasePool(nullptr) {} + static void* createAutoreleasePool(); + /** * @js NA * @lua NA - */ - ~Thread(); - /** + */ + static void releaseAutoreleasePool(void *autoreleasePool); + + /** To run a function in gl thread. * @js NA * @lua NA + @since v3.0 */ - void createAutoreleasePool(); + static void runOnGLThread(std::function f); + + /** Set how many callback functions being invoked per frame. Default value is 5. + * @js NA + * @lua NA + @since v3.0 + */ + static void setCallbackNumberPerFrame(long callbackNumberPerFrame); private: - void *_autoReleasePool; + // This function will be call by Director to call some call back function on gl thread + static void doCallback(); + + static std::list> *_callbackList; + static std::mutex *_mutex; + // How many callback functions invoked per frame + static long _callbackNumberPerFrame; }; // end of platform group diff --git a/cocos/2d/platform/apple/CCThread.mm b/cocos/2d/platform/apple/CCThread.mm index 80b319bae4..4e138fb889 100644 --- a/cocos/2d/platform/apple/CCThread.mm +++ b/cocos/2d/platform/apple/CCThread.mm @@ -26,14 +26,55 @@ THE SOFTWARE. NS_CC_BEGIN -Thread::~Thread() +std::list>* ThreadHelper::_callbackList = new std::list>(); +std::mutex* ThreadHelper::_mutex = new std::mutex; +long ThreadHelper::_callbackNumberPerFrame = 5; + +void* ThreadHelper::createAutoreleasePool() { - [(id)_autoReleasePool release]; + id pool = [[NSAutoreleasePool alloc] init]; + return pool; } -void Thread::createAutoreleasePool() +void ThreadHelper::releaseAutoreleasePool(void *autoreleasePool) { - _autoReleasePool = [[NSAutoreleasePool alloc] init]; + [(NSAutoreleasePool*)autoreleasePool release]; +} + +void ThreadHelper::runOnGLThread(std::function f) +{ + // Insert call back function + _mutex->lock(); + _callbackList->push_back(f); + _mutex->unlock(); +} + +void ThreadHelper::doCallback() +{ + _mutex->lock(); + auto iter = _callbackList->begin(); + long i = 0; + while (iter != _callbackList->end()) + { + auto f = *iter; + f(); + + ++i; + if (i >= _callbackNumberPerFrame) + { + break; + } + else + { + iter = _callbackList->erase(iter); + } + } + _mutex->unlock(); +} + +void ThreadHelper::setCallbackNumberPerFrame(long callbackNumberPerFrame) +{ + _callbackNumberPerFrame = callbackNumberPerFrame; } NS_CC_END diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 27b0a70bb8..b2c2e22295 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -155,8 +155,7 @@ void DataReaderHelper::loadData() while (true) { // create autorelease pool for iOS - Thread thread; - thread.createAutoreleasePool(); + auto autoreleasePool = ThreadHelper::createAutoreleasePool(); std::queue *pQueue = _asyncStructQueue; _asyncStructQueueMutex.lock(); // get async struct from queue @@ -200,6 +199,8 @@ void DataReaderHelper::loadData() _dataInfoMutex.lock(); _dataQueue->push(pDataInfo); _dataInfoMutex.unlock(); + + ThreadHelper::releaseAutoreleasePool(autoreleasePool); } if( _asyncStructQueue != nullptr ) From 2b43e72e7cbd97b474cf39538a61ea24edb080e4 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 27 Nov 2013 17:33:33 +0800 Subject: [PATCH 68/75] issue #2771: fix vs compile errors, change project setting --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/cocos2d.vcxproj | 16 +------- cocos/2d/cocos2d.vcxproj.filters | 41 +------------------ cocos/physics/CCPhysicsBody.cpp | 35 ++++++++-------- cocos/physics/CCPhysicsBody.h | 18 ++++---- cocos/physics/CCPhysicsShape.cpp | 39 +++++++++--------- cocos/physics/CCPhysicsWorld.cpp | 2 +- cocos/physics/CCPhysicsWorld.h | 1 + .../Classes/PhysicsTest/PhysicsTest.cpp | 8 ++-- .../Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 4 +- 11 files changed, 60 insertions(+), 108 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index f436fb8bc9..a9e8e103bc 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5221e6a74126a0c87cb3637082cf9035157a97f0 \ No newline at end of file +da0114d4d804843cb56ee8294fbe42f645c0183c \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index fe0929b0b5..3e5d5af3ae 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2461d13fd6f4fadc6ee396109932e50b1de8ed99 \ No newline at end of file +9fd236eacc216f0d21f06bfa698d92e28cc4a92a \ No newline at end of file diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 5180e1a6f9..72b52b3b97 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -74,7 +74,7 @@ Disabled $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_DEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks MultiThreadedDebugDLL @@ -121,7 +121,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(EngineRoot)external\sqlite3\include;$(EngineRoot)external\unzip;$(EngineRoot)external\tinyxml2;$(EngineRoot)external\png\include\win32;$(EngineRoot)external\jpeg\include\win32;$(EngineRoot)external\tiff\include\win32;$(EngineRoot)external\webp\include\win32;$(EngineRoot)external\freetype2\include\win32;$(EngineRoot)external\win32-specific\icon\include;$(EngineRoot)external\win32-specific\zlib\include;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;NDEBUG;_WINDOWS;_LIB;COCOS2DXWIN32_EXPORTS;GL_GLEXT_PROTOTYPES;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL @@ -192,11 +192,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - @@ -361,16 +356,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - - - - - - diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 9055db96e4..969c60324f 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -91,9 +91,6 @@ {aeadfa95-9c89-4212-98ae-89ad57db596a} - - {b9880458-36e5-4f28-a34b-d01d9512a395} - {05e27e68-7574-4a8b-af68-553dd3bafdfa} @@ -548,21 +545,6 @@ event_dispatcher - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - physics\chipmunk @@ -589,9 +571,6 @@ physics - - physics - physics @@ -1128,24 +1107,6 @@ event_dispatcher - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - - - physics\Box2D - physics\chipmunk @@ -1165,4 +1126,4 @@ physics\chipmunk - + \ No newline at end of file diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index ec8295b873..5378526c93 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -40,6 +40,7 @@ #include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN +extern const float PHYSICS_INFINITY; namespace { @@ -303,8 +304,8 @@ void PhysicsBody::setDynamic(bool dynamic) } // avoid incorrect collion simulation. - cpBodySetMass(_info->getBody(), INFINITY); - cpBodySetMoment(_info->getBody(), INFINITY); + cpBodySetMass(_info->getBody(), PHYSICS_INFINITY); + cpBodySetMoment(_info->getBody(), PHYSICS_INFINITY); cpBodySetVel(_info->getBody(), cpvzero); cpBodySetAngVel(_info->getBody(), 0.0f); } @@ -316,7 +317,7 @@ void PhysicsBody::setRotationEnable(bool enable) { if (_rotationEnable != enable) { - cpBodySetMoment(_info->getBody(), enable ? _moment : INFINITY); + cpBodySetMoment(_info->getBody(), enable ? _moment : PHYSICS_INFINITY); _rotationEnable = enable; } } @@ -442,9 +443,9 @@ void PhysicsBody::setMass(float mass) _massDefault = false; // update density - if (_mass == INFINITY) + if (_mass == PHYSICS_INFINITY) { - _density = INFINITY; + _density = PHYSICS_INFINITY; } else { @@ -466,17 +467,17 @@ void PhysicsBody::setMass(float mass) void PhysicsBody::addMass(float mass) { - if (mass == INFINITY) + if (mass == PHYSICS_INFINITY) { - _mass = INFINITY; + _mass = PHYSICS_INFINITY; _massDefault = false; - _density = INFINITY; + _density = PHYSICS_INFINITY; } - else if (mass == -INFINITY) + else if (mass == -PHYSICS_INFINITY) { return; } - else if (_mass != INFINITY) + else if (_mass != PHYSICS_INFINITY) { if (_massDefault) { @@ -512,21 +513,21 @@ void PhysicsBody::addMass(float mass) void PhysicsBody::addMoment(float moment) { - if (moment == INFINITY) + if (moment == PHYSICS_INFINITY) { - // if moment is INFINITY, the moment of the body will become INFINITY - _moment = INFINITY; + // if moment is PHYSICS_INFINITY, the moment of the body will become PHYSICS_INFINITY + _moment = PHYSICS_INFINITY; _momentDefault = false; } - else if (moment == -INFINITY) + else if (moment == -PHYSICS_INFINITY) { - // if moment is -INFINITY, it won't change + // if moment is -PHYSICS_INFINITY, it won't change return; } else { - // if moment of the body is INFINITY is has no effect - if (_moment != INFINITY) + // if moment of the body is PHYSICS_INFINITY is has no effect + if (_moment != PHYSICS_INFINITY) { if (_momentDefault) { diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index ebff4c777f..55699da85b 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -51,7 +51,7 @@ const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f); * A body affect by physics. * it can attach one or more shapes. * if you create body with createXXX, it will automatically compute mass and moment with density your specified(which is PHYSICSBODY_MATERIAL_DEFAULT by default, and the density value is 0.1f), and it based on the formular: mass = density * area. - * if you create body with createEdgeXXX, the mass and moment will be INFINITY by default. and it's a static body. + * if you create body with createEdgeXXX, the mass and moment will be PHYSICS_INFINITY by default. and it's a static body. * you can change mass and moment with setMass() and setMoment(). and you can change the body to be dynamic or static by use function setDynamic(). */ class PhysicsBody : public Object @@ -206,16 +206,16 @@ public: /** * @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 INFINITY, it will cause some unexpected result, please use addMass() instead. + * @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); /** get the body mass. */ inline float getMass() const { return _mass; } /** * @brief add mass to body. - * if _mass(mass of the body) == INFINITY, it remains. - * if mass == INFINITY, _mass will be INFINITY. - * if mass == -INFINITY, _mass will not change. + * 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; */ @@ -223,16 +223,16 @@ public: /** * @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 INFINITY, it will cause some unexpected result, please use addMoment() instead. + * @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); /** get the body moment of inertia. */ inline float getMoment(float moment) const { return _moment; } /** * @brief add moment of inertia to body. - * if _moment(moment of the body) == INFINITY, it remains. - * if moment == INFINITY, _moment will be INFINITY. - * if moment == -INFINITY, _moment will not change. + * 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; */ diff --git a/cocos/physics/CCPhysicsShape.cpp b/cocos/physics/CCPhysicsShape.cpp index d40c7c14a4..b045c433a6 100644 --- a/cocos/physics/CCPhysicsShape.cpp +++ b/cocos/physics/CCPhysicsShape.cpp @@ -37,6 +37,7 @@ #include "chipmunk/CCPhysicsHelper_chipmunk.h" NS_CC_BEGIN +extern const float PHYSICS_INFINITY; PhysicsShape::PhysicsShape() : _body(nullptr) @@ -198,9 +199,9 @@ void PhysicsShape::setDensity(float density) _material.density = density; - if (_material.density == INFINITY) + if (_material.density == PHYSICS_INFINITY) { - setMass(INFINITY); + setMass(PHYSICS_INFINITY); }else if (_area > 0) { setMass(PhysicsHelper::float2cpfloat(_material.density * _area)); @@ -306,7 +307,7 @@ bool PhysicsShapeCircle::init(float radius, const PhysicsMaterial& material/* = _info->add(shape); _area = calculateDefaultArea(); - _mass = material.density == INFINITY ? INFINITY : material.density * _area; + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; _moment = calculateDefaultMoment(); setMaterial(material); @@ -323,7 +324,7 @@ float PhysicsShapeCircle::calculateArea(float radius) float PhysicsShapeCircle::calculateMoment(float mass, float radius, const Point& offset) { - return mass == INFINITY ? INFINITY + return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(mass), 0, PhysicsHelper::float2cpfloat(radius), @@ -339,7 +340,7 @@ float PhysicsShapeCircle::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == INFINITY ? INFINITY + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForCircle(PhysicsHelper::float2cpfloat(_mass), 0, cpCircleShapeGetRadius(shape), @@ -385,8 +386,8 @@ bool PhysicsShapeEdgeSegment::init(const Point& a, const Point& b, const Physics _info->add(shape); - _mass = INFINITY; - _moment = INFINITY; + _mass = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; _center = a.getMidpoint(b); @@ -447,7 +448,7 @@ bool PhysicsShapeBox::init(const Size& size, const PhysicsMaterial& material/* = _offset = offset; _area = calculateDefaultArea(); - _mass = material.density == INFINITY ? INFINITY : material.density * _area; + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; _moment = calculateDefaultMoment(); setMaterial(material); @@ -476,7 +477,7 @@ float PhysicsShapeBox::calculateMoment(float mass, const Size& size, const Point {-wh.x/2.0f, -wh.y/2.0f}, {-wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, wh.y/2.0f}, {wh.x/2.0f, -wh.y/2.0f} }; - return mass == INFINITY ? INFINITY + return mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(PhysicsHelper::float2cpfloat(mass), 4, vec, @@ -492,7 +493,7 @@ float PhysicsShapeBox::calculateDefaultArea() float PhysicsShapeBox::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == INFINITY ? INFINITY + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } @@ -539,7 +540,7 @@ bool PhysicsShapePolygon::init(const Point* points, int count, const PhysicsMate _info->add(shape); _area = calculateDefaultArea(); - _mass = material.density == INFINITY ? INFINITY : material.density * _area; + _mass = material.density == PHYSICS_INFINITY ? PHYSICS_INFINITY : material.density * _area; _moment = calculateDefaultMoment(); _center = PhysicsHelper::cpv2point(cpCentroidForPoly(((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts)); @@ -565,7 +566,7 @@ float PhysicsShapePolygon::calculateMoment(float mass, const Point* points, int { cpVect* vecs = new cpVect[count]; PhysicsHelper::points2cpvs(points, vecs, count); - float moment = mass == INFINITY ? INFINITY + float moment = mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(mass, count, vecs, PhysicsHelper::point2cpv(offset))); CC_SAFE_DELETE_ARRAY(vecs); @@ -581,7 +582,7 @@ float PhysicsShapePolygon::calculateDefaultArea() float PhysicsShapePolygon::calculateDefaultMoment() { cpShape* shape = _info->getShapes().front(); - return _mass == INFINITY ? INFINITY + return _mass == PHYSICS_INFINITY ? PHYSICS_INFINITY : PhysicsHelper::cpfloat2float(cpMomentForPoly(_mass, ((cpPolyShape*)shape)->numVerts, ((cpPolyShape*)shape)->verts, cpvzero)); } @@ -643,8 +644,8 @@ bool PhysicsShapeEdgeBox::init(const Size& size, const PhysicsMaterial& material CC_BREAK_IF(i < 4); _offset = offset; - _mass = INFINITY; - _moment = INFINITY; + _mass = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; setMaterial(material); @@ -693,8 +694,8 @@ bool PhysicsShapeEdgePolygon::init(const Point* points, int count, const Physics CC_BREAK_IF(i < count); - _mass = INFINITY; - _moment = INFINITY; + _mass = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; setMaterial(material); @@ -754,8 +755,8 @@ bool PhysicsShapeEdgeChain::init(const Point* points, int count, const PhysicsMa CC_SAFE_DELETE_ARRAY(vec); CC_BREAK_IF(i < count); - _mass = INFINITY; - _moment = INFINITY; + _mass = PHYSICS_INFINITY; + _moment = PHYSICS_INFINITY; setMaterial(material); diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 2dc696bde6..e90f48b478 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -52,7 +52,7 @@ #include NS_CC_BEGIN - +const float PHYSICS_INFINITY = INFINITY; extern const char* PHYSICSCONTACT_EVENT_NAME; namespace diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 2b9f34d140..389cde4f2c 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -202,6 +202,7 @@ protected: friend class PhysicsWorld; }; +extern const float PHYSICS_INFINITY; NS_CC_END diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index dc84cc0540..c2c7778b65 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -384,7 +384,7 @@ bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) if (body != nullptr) { Node* mouse = Node::create(); - mouse->setPhysicsBody(PhysicsBody::create(INFINITY, INFINITY)); + mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); @@ -444,7 +444,7 @@ void PhysicsDemoLogoSmash::onEnter() 0.95f, PhysicsMaterial(0.01f, 0.0f, 0.0f)); ball->getPhysicsBody()->setMass(1.0); - ball->getPhysicsBody()->setMoment(INFINITY); + ball->getPhysicsBody()->setMoment(PHYSICS_INFINITY); _ball->addChild(ball); @@ -453,7 +453,7 @@ void PhysicsDemoLogoSmash::onEnter() } - auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(INFINITY, 0, 0)); + auto bullet = makeBall(Point(400, 0), 10, PhysicsMaterial(PHYSICS_INFINITY, 0, 0)); bullet->getPhysicsBody()->setVelocity(Point(400, 0)); bullet->setPosition(Point(-1000, VisibleRect::getVisibleRect().size.height/2)); @@ -835,7 +835,7 @@ void PhysicsDemoPump::onEnter() auto body = PhysicsBody::create(); body->setDynamic(false); - PhysicsMaterial staticMaterial(INFINITY, 0, 0.5f); + PhysicsMaterial staticMaterial(PHYSICS_INFINITY, 0, 0.5f); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(50, 0), VisibleRect::leftTop() + Point(50, -130), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(190, 0), VisibleRect::leftTop() + Point(100, -50), staticMaterial, 2.0f)); body->addShape(PhysicsShapeEdgeSegment::create(VisibleRect::leftTop() + Point(100, -50), VisibleRect::leftTop() + Point(100, -90), staticMaterial, 2.0f)); diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 1fd4a425d8..fcdc225b9e 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -70,7 +70,7 @@ Disabled ..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_USE_PHYSICS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL @@ -103,7 +103,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ MaxSpeed true ..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\network;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\curl\include\win32;$(EngineRoot)external\websockets\win32\include;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;CC_ENABLE_CHIPMUNK_INTEGRATION=1;CC_USE_PHYSICS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true From eded94ef76e41f6926183f3b1106405422e3ea1d Mon Sep 17 00:00:00 2001 From: minggo Date: Wed, 27 Nov 2013 17:43:54 +0800 Subject: [PATCH 69/75] don't create a pool, since it doesn't invoke any iOS dependent codes --- cocos/2d/CCTextureCache.cpp | 5 ----- cocos/editor-support/cocostudio/CCDataReaderHelper.cpp | 5 ----- 2 files changed, 10 deletions(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 6f4c521d3a..a16f85f28d 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -162,9 +162,6 @@ void TextureCache::loadImage() while (true) { - // create autorelease pool for iOS - auto autolreasePool = ThreadHelper::createAutoreleasePool(); - std::queue *pQueue = _asyncStructQueue; _asyncStructQueueMutex.lock(); if (pQueue->empty()) @@ -206,8 +203,6 @@ void TextureCache::loadImage() _imageInfoMutex.lock(); _imageInfoQueue->push(imageInfo); _imageInfoMutex.unlock(); - - ThreadHelper::releaseAutoreleasePool(autolreasePool); } if(_asyncStructQueue != nullptr) diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index b2c2e22295..00e1d7f3f4 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -154,9 +154,6 @@ void DataReaderHelper::loadData() while (true) { - // create autorelease pool for iOS - auto autoreleasePool = ThreadHelper::createAutoreleasePool(); - std::queue *pQueue = _asyncStructQueue; _asyncStructQueueMutex.lock(); // get async struct from queue if (pQueue->empty()) @@ -199,8 +196,6 @@ void DataReaderHelper::loadData() _dataInfoMutex.lock(); _dataQueue->push(pDataInfo); _dataInfoMutex.unlock(); - - ThreadHelper::releaseAutoreleasePool(autoreleasePool); } if( _asyncStructQueue != nullptr ) From 4615eae22fb2ce88bed2670e93612646268b1d45 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Wed, 27 Nov 2013 18:30:48 +0800 Subject: [PATCH 70/75] =?UTF-8?q?issue=20#2771:remove=20unneeded=20include?= =?UTF-8?q?=20=E2=80=9CccConfig.h=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/physics/CCPhysicsBody.h | 1 - cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp | 1 - 2 files changed, 2 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 55699da85b..f6d2e91f71 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -27,7 +27,6 @@ #ifdef CC_USE_PHYSICS -#include "ccConfig.h" #include "CCObject.h" #include "CCGeometry.h" #include "CCArray.h" diff --git a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp index 56478d4ac9..fd218e1575 100644 --- a/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp +++ b/cocos/physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp @@ -23,7 +23,6 @@ ****************************************************************************/ #ifdef CC_USE_PHYSICS -#include "ccConfig.h" #include "CCPhysicsWorldInfo_chipmunk.h" #include "CCPhysicsHelper_chipmunk.h" #include "CCPhysicsBodyInfo_chipmunk.h" From c78ce63f141ab1e5b59005691ccfd449b023d71c Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 28 Nov 2013 11:06:08 +0800 Subject: [PATCH 71/75] use ThreadHelper::runOnGLThread() in AssetsManager --- extensions/assets-manager/AssetsManager.cpp | 218 ++++++-------------- extensions/assets-manager/AssetsManager.h | 34 --- 2 files changed, 60 insertions(+), 192 deletions(-) diff --git a/extensions/assets-manager/AssetsManager.cpp b/extensions/assets-manager/AssetsManager.cpp index 0a7b9c8c4b..aefb9fc978 100644 --- a/extensions/assets-manager/AssetsManager.cpp +++ b/extensions/assets-manager/AssetsManager.cpp @@ -86,15 +86,10 @@ AssetsManager::AssetsManager(const char* packageUrl/* =NULL */, const char* vers , _shouldDeleteDelegateWhenExit(false) { checkStoragePath(); - _schedule = new Helper(); } AssetsManager::~AssetsManager() { - if (_schedule) - { - _schedule->release(); - } if (_shouldDeleteDelegateWhenExit) { delete _delegate; @@ -161,7 +156,10 @@ bool AssetsManager::checkUpdate() if (res != 0) { - sendErrorMessage(ErrorCode::NETWORK); + ThreadHelper::runOnGLThread([&, this]{ + if (this->_delegate) + this->_delegate->onError(ErrorCode::NETWORK); + }); CCLOG("can not get version file content, error code is %d", res); curl_easy_cleanup(_curl); return false; @@ -170,7 +168,10 @@ bool AssetsManager::checkUpdate() string recordedVersion = UserDefault::getInstance()->getStringForKey(keyOfVersion().c_str()); if (recordedVersion == _version) { - sendErrorMessage(ErrorCode::NO_NEW_VERSION); + ThreadHelper::runOnGLThread([&, this]{ + if (this->_delegate) + this->_delegate->onError(ErrorCode::NO_NEW_VERSION); + }); CCLOG("there is not new version"); // Set resource search path. setSearchPath(); @@ -190,25 +191,45 @@ void AssetsManager::downloadAndUncompress() { if (! downLoad()) break; - // Record downloaded version. - AssetsManager::Message *msg1 = new AssetsManager::Message(); - msg1->what = ASSETSMANAGER_MESSAGE_RECORD_DOWNLOADED_VERSION; - msg1->obj = this; - _schedule->sendMessage(msg1); + ThreadHelper::runOnGLThread([&, this]{ + UserDefault::getInstance()->setStringForKey(this->keyOfDownloadedVersion().c_str(), + this->_version.c_str()); + UserDefault::getInstance()->flush(); + }); } // Uncompress zip file. if (! uncompress()) { - sendErrorMessage(ErrorCode::UNCOMPRESS); + ThreadHelper::runOnGLThread([&, this]{ + if (this->_delegate) + this->_delegate->onError(ErrorCode::UNCOMPRESS); + }); break; } - // Record updated version and remove downloaded zip file - AssetsManager::Message *msg2 = new AssetsManager::Message(); - msg2->what = ASSETSMANAGER_MESSAGE_UPDATE_SUCCEED; - msg2->obj = this; - _schedule->sendMessage(msg2); + ThreadHelper::runOnGLThread([&, this] { + + // Record new version code. + UserDefault::getInstance()->setStringForKey(this->keyOfVersion().c_str(), this->_version.c_str()); + + // Unrecord downloaded version code. + UserDefault::getInstance()->setStringForKey(this->keyOfDownloadedVersion().c_str(), ""); + UserDefault::getInstance()->flush(); + + // Set resource search path. + this->setSearchPath(); + + // Delete unloaded zip file. + string zipfileName = this->_storagePath + TEMP_PACKAGE_FILE_NAME; + if (remove(zipfileName.c_str()) != 0) + { + CCLOG("can not remove downloaded zip file %s", zipfileName.c_str()); + } + + if (this->_delegate) this->_delegate->onSuccess(); + }); + } while (0); _isDownloading = false; @@ -452,18 +473,20 @@ static size_t downLoadPackage(void *ptr, size_t size, size_t nmemb, void *userda int assetsManagerProgressFunc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded) { - AssetsManager* manager = (AssetsManager*)ptr; - AssetsManager::Message *msg = new AssetsManager::Message(); - msg->what = ASSETSMANAGER_MESSAGE_PROGRESS; + static int percent = 0; + int tmp = (int)(nowDownloaded / totalToDownload * 100); - ProgressMessage *progressData = new ProgressMessage(); - progressData->percent = (int)(nowDownloaded/totalToDownload*100); - progressData->manager = manager; - msg->obj = progressData; - - manager->_schedule->sendMessage(msg); - - CCLOG("downloading... %d%%", (int)(nowDownloaded/totalToDownload*100)); + if (percent != tmp) + { + percent = tmp; + ThreadHelper::runOnGLThread([=]{ + auto manager = static_cast(ptr); + if (manager->_delegate) + manager->_delegate->onProgress(percent); + }); + + CCLOG("downloading... %d%%", percent); + } return 0; } @@ -475,7 +498,10 @@ bool AssetsManager::downLoad() FILE *fp = fopen(outFileName.c_str(), "wb"); if (! fp) { - sendErrorMessage(ErrorCode::CREATE_FILE); + ThreadHelper::runOnGLThread([&, this]{ + if (this->_delegate) + this->_delegate->onError(ErrorCode::CREATE_FILE); + }); CCLOG("can not create file %s", outFileName.c_str()); return false; } @@ -492,7 +518,10 @@ bool AssetsManager::downLoad() curl_easy_cleanup(_curl); if (res != 0) { - sendErrorMessage(ErrorCode::NETWORK); + ThreadHelper::runOnGLThread([&, this]{ + if (this->_delegate) + this->_delegate->onError(ErrorCode::NETWORK); + }); CCLOG("error when download package"); fclose(fp); return false; @@ -560,133 +589,6 @@ unsigned int AssetsManager::getConnectionTimeout() return _connectionTimeout; } -void AssetsManager::sendErrorMessage(AssetsManager::ErrorCode code) -{ - Message *msg = new Message(); - msg->what = ASSETSMANAGER_MESSAGE_ERROR; - - ErrorMessage *errorMessage = new ErrorMessage(); - errorMessage->code = code; - errorMessage->manager = this; - msg->obj = errorMessage; - - _schedule->sendMessage(msg); -} - -// Implementation of AssetsManagerHelper - -AssetsManager::Helper::Helper() -{ - _messageQueue = new list(); - Director::getInstance()->getScheduler()->scheduleUpdateForTarget(this, 0, false); -} - -AssetsManager::Helper::~Helper() -{ - Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); - delete _messageQueue; -} - -void AssetsManager::Helper::sendMessage(Message *msg) -{ - _messageQueueMutex.lock(); - _messageQueue->push_back(msg); - _messageQueueMutex.unlock(); -} - -void AssetsManager::Helper::update(float dt) -{ - Message *msg = NULL; - - // Returns quickly if no message - _messageQueueMutex.lock(); - if (0 == _messageQueue->size()) - { - _messageQueueMutex.unlock(); - return; - } - //remove unnecessary message - std::list::iterator it; - Message *proMsg = nullptr; - for (it = _messageQueue->begin(); it != _messageQueue->end(); ++it) - { - if((*it)->what == ASSETSMANAGER_MESSAGE_PROGRESS) - { - if (proMsg) - { - _messageQueue->remove(proMsg); - delete (ProgressMessage*)proMsg->obj; - delete proMsg; - } - proMsg = *it; - } - } - // Gets message - msg = *(_messageQueue->begin()); - _messageQueue->pop_front(); - _messageQueueMutex.unlock(); - - switch (msg->what) { - case ASSETSMANAGER_MESSAGE_UPDATE_SUCCEED: - handleUpdateSucceed(msg); - - break; - case ASSETSMANAGER_MESSAGE_RECORD_DOWNLOADED_VERSION: - UserDefault::getInstance()->setStringForKey(((AssetsManager*)msg->obj)->keyOfDownloadedVersion().c_str(), - ((AssetsManager*)msg->obj)->_version.c_str()); - UserDefault::getInstance()->flush(); - - break; - case ASSETSMANAGER_MESSAGE_PROGRESS: - if (((ProgressMessage*)msg->obj)->manager->_delegate) - { - ((ProgressMessage*)msg->obj)->manager->_delegate->onProgress(((ProgressMessage*)msg->obj)->percent); - } - - delete (ProgressMessage*)msg->obj; - - break; - case ASSETSMANAGER_MESSAGE_ERROR: - // error call back - if (((ErrorMessage*)msg->obj)->manager->_delegate) - { - ((ErrorMessage*)msg->obj)->manager->_delegate->onError(((ErrorMessage*)msg->obj)->code); - } - - delete ((ErrorMessage*)msg->obj); - - break; - default: - break; - } - - delete msg; -} - -void AssetsManager::Helper::handleUpdateSucceed(Message *msg) -{ - AssetsManager* manager = (AssetsManager*)msg->obj; - - // Record new version code. - UserDefault::getInstance()->setStringForKey(manager->keyOfVersion().c_str(), manager->_version.c_str()); - - // Unrecord downloaded version code. - UserDefault::getInstance()->setStringForKey(manager->keyOfDownloadedVersion().c_str(), ""); - UserDefault::getInstance()->flush(); - - // Set resource search path. - manager->setSearchPath(); - - // Delete unloaded zip file. - string zipfileName = manager->_storagePath + TEMP_PACKAGE_FILE_NAME; - if (remove(zipfileName.c_str()) != 0) - { - CCLOG("can not remove downloaded zip file %s", zipfileName.c_str()); - } - - if (manager->_delegate) manager->_delegate->onSuccess(); -} - AssetsManager* AssetsManager::create(const char* packageUrl, const char* versionFileUrl, const char* storagePath, ErrorCallback errorCallback, ProgressCallback progressCallback, SuccessCallback successCallback ) { class DelegateProtocolImpl : public AssetsManagerDelegateProtocol diff --git a/extensions/assets-manager/AssetsManager.h b/extensions/assets-manager/AssetsManager.h index 2cc253c165..e37ee4b3d9 100644 --- a/extensions/assets-manager/AssetsManager.h +++ b/extensions/assets-manager/AssetsManager.h @@ -166,40 +166,7 @@ protected: bool uncompress(); bool createDirectory(const char *path); void setSearchPath(); - void sendErrorMessage(ErrorCode code); void downloadAndUncompress(); - -private: - typedef struct _Message - { - public: - _Message() : what(0), obj(NULL){} - unsigned int what; // message type - void* obj; - } Message; - - class Helper : public cocos2d::Object - { - public: - /** - * @js ctor - */ - Helper(); - /** - * @js NA - * @lua NA - */ - ~Helper(); - - virtual void update(float dt); - void sendMessage(Message *msg); - - private: - void handleUpdateSucceed(Message *msg); - - std::list *_messageQueue; - std::mutex _messageQueueMutex; - }; private: /** @brief Initializes storage path. @@ -224,7 +191,6 @@ private: void *_curl; - Helper *_schedule; unsigned int _connectionTimeout; AssetsManagerDelegateProtocol *_delegate; From a24af527a32c3b61183ac0096c17982ab62c0623 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 28 Nov 2013 03:14:39 +0000 Subject: [PATCH 72/75] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 3f5c6fd908..8b8a881547 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 3f5c6fd9082864d9dc214ce225e1515df279406d +Subproject commit 8b8a8815474b2dcef3de12161bf7c0621f3c3e05 From 1c55c207bf910e6108178263583e1d644090b4a3 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 28 Nov 2013 11:55:18 +0800 Subject: [PATCH 73/75] update project setting --- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- external/Box2D/proj.win32/Box2D.vcxproj | 2 ++ external/Box2D/proj.win32/Box2D.vcxproj.filters | 6 ++++++ samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 5 +++++ .../TestCpp/proj.win32/TestCpp.vcxproj.filters | 15 +++++++++++++++ 6 files changed, 30 insertions(+), 2 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 6392a6b63e..c629d20974 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -5d37163416155a0050b068b30de3aabc6e0b4013 \ No newline at end of file +8c433de9af68bb9698221528aae4b09667f8ac9b \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index a1b5294787..928fad27d5 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1e608aab69f45820f3120339ca3d1610a8a60a7f \ No newline at end of file +bd4602f32e671e4ffe20abd632f5b861b2025d05 \ No newline at end of file diff --git a/external/Box2D/proj.win32/Box2D.vcxproj b/external/Box2D/proj.win32/Box2D.vcxproj index cd4bd2086c..ed59a2460d 100644 --- a/external/Box2D/proj.win32/Box2D.vcxproj +++ b/external/Box2D/proj.win32/Box2D.vcxproj @@ -131,6 +131,7 @@ + @@ -178,6 +179,7 @@ + diff --git a/external/Box2D/proj.win32/Box2D.vcxproj.filters b/external/Box2D/proj.win32/Box2D.vcxproj.filters index e810cbb0cf..d9f5647a06 100644 --- a/external/Box2D/proj.win32/Box2D.vcxproj.filters +++ b/external/Box2D/proj.win32/Box2D.vcxproj.filters @@ -159,6 +159,9 @@ Rope + + Dynamics\Joints + @@ -297,5 +300,8 @@ Rope + + Dynamics\Joints + \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 1fd4a425d8..cfd32fc8e8 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -270,6 +270,11 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + + + + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index b51716ad85..dafeb94a8f 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -1279,5 +1279,20 @@ Classes\InputTest + + Classes\Box2DTestBed\Tests + + + Classes\Box2DTestBed\Tests + + + Classes\Box2DTestBed\Tests + + + Classes\Box2DTestBed\Tests + + + Classes\Box2DTestBed\Tests + \ No newline at end of file From 0ff2e65467a01c40d9fa44a195cebc551f704ec6 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 28 Nov 2013 15:41:23 +0800 Subject: [PATCH 74/75] reset cmakelists.txt --- external/Box2D/CMakeLists.txt | 261 ++++++++-------------------------- 1 file changed, 58 insertions(+), 203 deletions(-) diff --git a/external/Box2D/CMakeLists.txt b/external/Box2D/CMakeLists.txt index b800bcccbc..36a068b720 100644 --- a/external/Box2D/CMakeLists.txt +++ b/external/Box2D/CMakeLists.txt @@ -1,207 +1,62 @@ -set(BOX2D_Collision_SRCS - Collision/b2BroadPhase.cpp - Collision/b2CollideCircle.cpp - Collision/b2CollideEdge.cpp - Collision/b2CollidePolygon.cpp - Collision/b2Collision.cpp - Collision/b2Distance.cpp - Collision/b2DynamicTree.cpp - Collision/b2TimeOfImpact.cpp +set(BOX2D_SRC + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2PolygonShape.cpp + Collision/b2BroadPhase.cpp + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Distance.cpp + Collision/b2DynamicTree.cpp + Collision/b2TimeOfImpact.cpp + Common/b2BlockAllocator.cpp + Common/b2Draw.cpp + Common/b2Math.cpp + Common/b2Settings.cpp + Common/b2StackAllocator.cpp + Common/b2Timer.cpp + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2PolygonContact.cpp + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2MotorJoint.cpp + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WheelJoint.cpp + Dynamics/b2Body.cpp + Dynamics/b2ContactManager.cpp + Dynamics/b2Fixture.cpp + Dynamics/b2Island.cpp + Dynamics/b2World.cpp + Dynamics/b2WorldCallbacks.cpp + Rope/b2Rope.cpp ) -set(BOX2D_Collision_HDRS - Collision/b2BroadPhase.h - Collision/b2Collision.h - Collision/b2Distance.h - Collision/b2DynamicTree.h - Collision/b2TimeOfImpact.h -) -set(BOX2D_Shapes_SRCS - Collision/Shapes/b2CircleShape.cpp - Collision/Shapes/b2EdgeShape.cpp - Collision/Shapes/b2ChainShape.cpp - Collision/Shapes/b2PolygonShape.cpp -) -set(BOX2D_Shapes_HDRS - Collision/Shapes/b2CircleShape.h - Collision/Shapes/b2EdgeShape.h - Collision/Shapes/b2ChainShape.h - Collision/Shapes/b2PolygonShape.h - Collision/Shapes/b2Shape.h -) -set(BOX2D_Common_SRCS - Common/b2BlockAllocator.cpp - Common/b2Draw.cpp - Common/b2Math.cpp - Common/b2Settings.cpp - Common/b2StackAllocator.cpp - Common/b2Timer.cpp -) -set(BOX2D_Common_HDRS - Common/b2BlockAllocator.h - Common/b2Draw.h - Common/b2GrowableStack.h - Common/b2Math.h - Common/b2Settings.h - Common/b2StackAllocator.h - Common/b2Timer.h -) -set(BOX2D_Dynamics_SRCS - Dynamics/b2Body.cpp - Dynamics/b2ContactManager.cpp - Dynamics/b2Fixture.cpp - Dynamics/b2Island.cpp - Dynamics/b2World.cpp - Dynamics/b2WorldCallbacks.cpp -) -set(BOX2D_Dynamics_HDRS - Dynamics/b2Body.h - Dynamics/b2ContactManager.h - Dynamics/b2Fixture.h - Dynamics/b2Island.h - Dynamics/b2TimeStep.h - Dynamics/b2World.h - Dynamics/b2WorldCallbacks.h -) -set(BOX2D_Contacts_SRCS - Dynamics/Contacts/b2CircleContact.cpp - Dynamics/Contacts/b2Contact.cpp - Dynamics/Contacts/b2ContactSolver.cpp - Dynamics/Contacts/b2PolygonAndCircleContact.cpp - Dynamics/Contacts/b2EdgeAndCircleContact.cpp - Dynamics/Contacts/b2EdgeAndPolygonContact.cpp - Dynamics/Contacts/b2ChainAndCircleContact.cpp - Dynamics/Contacts/b2ChainAndPolygonContact.cpp - Dynamics/Contacts/b2PolygonContact.cpp -) -set(BOX2D_Contacts_HDRS - Dynamics/Contacts/b2CircleContact.h - Dynamics/Contacts/b2Contact.h - Dynamics/Contacts/b2ContactSolver.h - Dynamics/Contacts/b2PolygonAndCircleContact.h - Dynamics/Contacts/b2EdgeAndCircleContact.h - Dynamics/Contacts/b2EdgeAndPolygonContact.h - Dynamics/Contacts/b2ChainAndCircleContact.h - Dynamics/Contacts/b2ChainAndPolygonContact.h - Dynamics/Contacts/b2PolygonContact.h -) -set(BOX2D_Joints_SRCS - Dynamics/Joints/b2DistanceJoint.cpp - Dynamics/Joints/b2FrictionJoint.cpp - Dynamics/Joints/b2GearJoint.cpp - Dynamics/Joints/b2Joint.cpp - Dynamics/Joints/b2MotorJoint.cpp - Dynamics/Joints/b2MouseJoint.cpp - Dynamics/Joints/b2PrismaticJoint.cpp - Dynamics/Joints/b2PulleyJoint.cpp - Dynamics/Joints/b2RevoluteJoint.cpp - Dynamics/Joints/b2RopeJoint.cpp - Dynamics/Joints/b2WeldJoint.cpp - Dynamics/Joints/b2WheelJoint.cpp -) -set(BOX2D_Joints_HDRS - Dynamics/Joints/b2DistanceJoint.h - Dynamics/Joints/b2FrictionJoint.h - Dynamics/Joints/b2GearJoint.h - Dynamics/Joints/b2Joint.h - Dynamics/Joints/b2MotorJoint.h - Dynamics/Joints/b2MouseJoint.h - Dynamics/Joints/b2PrismaticJoint.h - Dynamics/Joints/b2PulleyJoint.h - Dynamics/Joints/b2RevoluteJoint.h - Dynamics/Joints/b2RopeJoint.h - Dynamics/Joints/b2WeldJoint.h - Dynamics/Joints/b2WheelJoint.h -) -set(BOX2D_Rope_SRCS - Rope/b2Rope.cpp -) -set(BOX2D_Rope_HDRS - Rope/b2Rope.h -) -set(BOX2D_General_HDRS - Box2D.h -) -include_directories( ../ ) -if(BOX2D_BUILD_SHARED) - add_library(Box2D_shared SHARED - ${BOX2D_General_HDRS} - ${BOX2D_Joints_SRCS} - ${BOX2D_Joints_HDRS} - ${BOX2D_Contacts_SRCS} - ${BOX2D_Contacts_HDRS} - ${BOX2D_Dynamics_SRCS} - ${BOX2D_Dynamics_HDRS} - ${BOX2D_Common_SRCS} - ${BOX2D_Common_HDRS} - ${BOX2D_Shapes_SRCS} - ${BOX2D_Shapes_HDRS} - ${BOX2D_Collision_SRCS} - ${BOX2D_Collision_HDRS} - ${BOX2D_Rope_SRCS} - ${BOX2D_Rope_HDRS} - ) - set_target_properties(Box2D_shared PROPERTIES - OUTPUT_NAME "Box2D" - CLEAN_DIRECT_OUTPUT 1 - VERSION ${BOX2D_VERSION} - ) -endif() +include_directories( + .. +) -if(BOX2D_BUILD_STATIC) - add_library(Box2D STATIC - ${BOX2D_General_HDRS} - ${BOX2D_Joints_SRCS} - ${BOX2D_Joints_HDRS} - ${BOX2D_Contacts_SRCS} - ${BOX2D_Contacts_HDRS} - ${BOX2D_Dynamics_SRCS} - ${BOX2D_Dynamics_HDRS} - ${BOX2D_Common_SRCS} - ${BOX2D_Common_HDRS} - ${BOX2D_Shapes_SRCS} - ${BOX2D_Shapes_HDRS} - ${BOX2D_Collision_SRCS} - ${BOX2D_Collision_HDRS} - ${BOX2D_Rope_SRCS} - ${BOX2D_Rope_HDRS} - ) - set_target_properties(Box2D PROPERTIES - CLEAN_DIRECT_OUTPUT 1 - VERSION ${BOX2D_VERSION} - ) -endif() +add_library(box2d STATIC + ${BOX2D_SRC} +) -# These are used to create visual studio folders. -source_group(Collision FILES ${BOX2D_Collision_SRCS} ${BOX2D_Collision_HDRS}) -source_group(Collision\\Shapes FILES ${BOX2D_Shapes_SRCS} ${BOX2D_Shapes_HDRS}) -source_group(Common FILES ${BOX2D_Common_SRCS} ${BOX2D_Common_HDRS}) -source_group(Dynamics FILES ${BOX2D_Dynamics_SRCS} ${BOX2D_Dynamics_HDRS}) -source_group(Dynamics\\Contacts FILES ${BOX2D_Contacts_SRCS} ${BOX2D_Contacts_HDRS}) -source_group(Dynamics\\Joints FILES ${BOX2D_Joints_SRCS} ${BOX2D_Joints_HDRS}) -source_group(Include FILES ${BOX2D_General_HDRS}) -source_group(Rope FILES ${BOX2D_Rope_SRCS} ${BOX2D_Rope_HDRS}) - -if(BOX2D_INSTALL) - # install headers - install(FILES ${BOX2D_General_HDRS} DESTINATION include/Box2D) - install(FILES ${BOX2D_Collision_HDRS} DESTINATION include/Box2D/Collision) - install(FILES ${BOX2D_Shapes_HDRS} DESTINATION include/Box2D/Collision/Shapes) - install(FILES ${BOX2D_Common_HDRS} DESTINATION include/Box2D/Common) - install(FILES ${BOX2D_Dynamics_HDRS} DESTINATION include/Box2D/Dynamics) - install(FILES ${BOX2D_Contacts_HDRS} DESTINATION include/Box2D/Dynamics/Contacts) - install(FILES ${BOX2D_Joints_HDRS} DESTINATION include/Box2D/Dynamics/Joints) - install(FILES ${BOX2D_Rope_HDRS} DESTINATION include/Box2D/Rope) - - # install libraries - if(BOX2D_BUILD_SHARED) - install(TARGETS Box2D_shared EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}) - endif() - if(BOX2D_BUILD_STATIC) - install(TARGETS Box2D EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}) - endif() - - # install build system hooks for third-party apps - install(EXPORT Box2D-targets DESTINATION ${LIB_INSTALL_DIR}/Box2D) - install(FILES Box2DConfig.cmake DESTINATION ${LIB_INSTALL_DIR}/Box2D) -endif(BOX2D_INSTALL) +set_target_properties(box2d + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" +) From d3076a14154271ce16907a3f39320ce5ac251d09 Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 28 Nov 2013 16:09:21 +0800 Subject: [PATCH 75/75] [ci skip] --- CHANGELOG | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 8a5ecb030f..6e593585b2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,7 @@ cocos2d-x-3.0beta0 ?? 2013 +[All] + [NEW] Upgrated Box2D to 2.3.0 + [NEW] Added ThreadHelper, ThreadHelper::runOnGLThread() simplify invoking engine codes and OpenGL ES commands in a thread other then gl thread. [Android] [NEW] build/android-build.sh: add supporting to generate .apk file [FIX] XMLHttpRequest receives wrong binary array.