Merge branch 'v3' into v3_comments

This commit is contained in:
Huabing.Xu 2015-03-23 20:00:31 +08:00
commit 2dde1e69e3
237 changed files with 10088 additions and 5357 deletions

View File

@ -710,6 +710,7 @@ Developers:
Updates spine runtime.
Fixed a potential bug in Data's copy constructor.
Fixed the bug that MotionStreak can not work with MoveTo and MoveBy
Fixed a bug that HttpAsynConnection can not get error content if response code less than 200 or response code greater or equal than 300
luocker
Fix a bug that string itself is also modified in `String::componentsSeparatedByString`.

View File

@ -1,8 +1,9 @@
cocos2d-x-3.5 Mar.20 2015
cocos2d-x-3.5 Mar.23 2015
[NEW] EditBox: support Color4B
[FIX] AutoRelasePool: memory leak if adding an element into pool when releasing auto release pool
[FIX] FileUtils: getWritablePath() will not return corrent setted writable path on Mac & Windows
[FIX] FileUtils: getWritablePath() does not return corret setted writable path on Mac & Windows
[FIX] HttpAsynConnection: can not get error content if response code less than 200 or response code greater or equal than 300
cocos2d-x-3.5rc0 Mar.13 2015
[NEW] CocosStudio: add callback when loading a CSB file
@ -21,7 +22,7 @@ cocos2d-x-3.5rc0 Mar.13 2015
cocos2d-x-3.5beta0 Feb.27 2015
[NEW] Added Particle3D
[NEW] C++: add Romanian languange support
[NEW] C++: add Romanian language support
[FIX] Audio: audio can not resume if it is interrupt, and back from background
[FIX] Cocos Studio UI: setCameraMask does not work for the Cocos Studio UI

View File

@ -38,7 +38,7 @@ endif()
project (Cocos2d-X)
# The version number
set(COCOS2D_X_VERSION 3.5beta0)
set(COCOS2D_X_VERSION 3.5)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake/Modules/")
include(CocosBuildHelpers)

View File

@ -816,6 +816,8 @@
B2507B6C192589AF00FA4972 /* Shaders3D in Resources */ = {isa = PBXBuildFile; fileRef = B2507B6A192589AF00FA4972 /* Shaders3D */; };
B609E67319C18DAD003D0074 /* BillBoardTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B609E67119C18DAD003D0074 /* BillBoardTest.cpp */; };
B609E67419C18DAD003D0074 /* BillBoardTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B609E67119C18DAD003D0074 /* BillBoardTest.cpp */; };
B6337DF71ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B6337DF51ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp */; };
B6337DF81ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B6337DF51ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp */; };
B639932E1A490EC700B07923 /* Particle3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B639932C1A490EC700B07923 /* Particle3DTest.cpp */; };
B639932F1A490EC700B07923 /* Particle3DTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B639932C1A490EC700B07923 /* Particle3DTest.cpp */; };
B63993311A49359F00B07923 /* Particle3D in Resources */ = {isa = PBXBuildFile; fileRef = B63993301A49359F00B07923 /* Particle3D */; };
@ -1752,6 +1754,8 @@
B2507B6A192589AF00FA4972 /* Shaders3D */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Shaders3D; path = "../tests/cpp-tests/Resources/Shaders3D"; sourceTree = "<group>"; };
B609E67119C18DAD003D0074 /* BillBoardTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = BillBoardTest.cpp; path = BillBoardTest/BillBoardTest.cpp; sourceTree = "<group>"; };
B609E67219C18DAD003D0074 /* BillBoardTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = BillBoardTest.h; path = BillBoardTest/BillBoardTest.h; sourceTree = "<group>"; };
B6337DF51ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PerformanceParticle3DTest.cpp; sourceTree = "<group>"; };
B6337DF61ABA9B44005AEF24 /* PerformanceParticle3DTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PerformanceParticle3DTest.h; sourceTree = "<group>"; };
B639932C1A490EC700B07923 /* Particle3DTest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Particle3DTest.cpp; path = Particle3DTest/Particle3DTest.cpp; sourceTree = "<group>"; };
B639932D1A490EC700B07923 /* Particle3DTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Particle3DTest.h; path = Particle3DTest/Particle3DTest.h; sourceTree = "<group>"; };
B63993301A49359F00B07923 /* Particle3D */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Particle3D; path = "../tests/cpp-tests/Resources/Particle3D"; sourceTree = "<group>"; };
@ -2939,6 +2943,8 @@
1AC35AC118CECF0C00F37B72 /* PerformanceTest */ = {
isa = PBXGroup;
children = (
B6337DF51ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp */,
B6337DF61ABA9B44005AEF24 /* PerformanceParticle3DTest.h */,
1AC35AC218CECF0C00F37B72 /* PerformanceAllocTest.cpp */,
1AC35AC318CECF0C00F37B72 /* PerformanceAllocTest.h */,
1AF152D718FD252A00A52F3D /* PerformanceCallbackTest.cpp */,
@ -4866,6 +4872,7 @@
182C5CBA1A95B2FD00C30D34 /* CocosStudio3DTest.cpp in Sources */,
1AC35C5D18CECF0C00F37B72 /* Ball.cpp in Sources */,
1AC35B7B18CECF0C00F37B72 /* GameOverScene.cpp in Sources */,
B6337DF71ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp in Sources */,
1AC35BF318CECF0C00F37B72 /* ExtensionsTest.cpp in Sources */,
1AC35B3518CECF0C00F37B72 /* TestEntries.cpp in Sources */,
1AC35B2D18CECF0C00F37B72 /* Box2dTest.cpp in Sources */,
@ -5118,6 +5125,7 @@
1AC35C3E18CECF0C00F37B72 /* PhysicsTest.cpp in Sources */,
3825CC4A1A2C982A00C92EA8 /* CustomRootNode.cpp in Sources */,
29080DC6191B595E0066F8DF /* UIScene_Editor.cpp in Sources */,
B6337DF81ABA9B44005AEF24 /* PerformanceParticle3DTest.cpp in Sources */,
29080DB2191B595E0066F8DF /* UILayoutTest.cpp in Sources */,
1AC35B6A18CECF0C00F37B72 /* ButtonTestLayer.cpp in Sources */,
29080DB6191B595E0066F8DF /* UIListViewTest.cpp in Sources */,

View File

@ -66,6 +66,7 @@ public:
/** Returns a new action that performs the exactly the reverse action.
*
* @return A new action that performs the exactly the reverse action.
* @js NA
*/
virtual Action* reverse() const
{
@ -319,6 +320,7 @@ public:
virtual Follow* reverse() const override;
/**
* @param dt in seconds.
* @js NA
*/
virtual void step(float dt) override;
virtual bool isDone() const override;

View File

@ -65,32 +65,38 @@ public:
/* Sets the Eye value of the Camera.
*
* @param eye The Eye value of the Camera.
* @js NA
*/
void setEye(const Vec3 &eye);
void setEye(float x, float y, float z);
/* Returns the Eye value of the Camera.
*
* @return The Eye value of the Camera.
* @js NA
*/
const Vec3& getEye() const { return _eye; }
/* Sets the Center value of the Camera.
*
* @param center The Center value of the Camera.
* @js NA
*/
void setCenter(const Vec3 &center);
/* Returns the Center value of the Camera.
*
* @return The Center value of the Camera.
* @js NA
*/
const Vec3& getCenter() const { return _center; }
/* Sets the Up value of the Camera.
*
* @param up The Up value of the Camera.
* @js NA
*/
void setUp(const Vec3 &up);
/* Returns the Up value of the Camera.
*
* @return The Up value of the Camera.
* @js NA
*/
const Vec3& getUp() const { return _up; }

View File

@ -52,6 +52,7 @@ class Node;
/** An Array that contain control points.
* Used by CardinalSplineTo and (By) and CatmullRomTo (and By) actions.
* @ingroup Actions
* @js NA
*/
class CC_DLL PointArray : public Ref, public Clonable
{
@ -182,7 +183,7 @@ public:
*/
virtual ~CardinalSplineTo();
/**
* @js NA
* @js ctor
* @lua NA
*/
CardinalSplineTo();

View File

@ -391,7 +391,6 @@ CC_CONSTRUCTOR_ACCESS:
CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Ref* target);
/** initializes the action with the std::function<void()>
* @js NA
* @lua NA
*/
bool initWithFunction(const std::function<void()>& func);
@ -415,6 +414,7 @@ private:
/** @class CallFuncN
* @brief Calls a 'callback' with the node as the first argument. N means Node.
* @js NA
*/
class CC_DLL CallFuncN : public CallFunc
{
@ -466,6 +466,7 @@ private:
* @deprecated Please use CallFuncN instead.
* @brief Calls a 'callback' with the node as the first argument and the 2nd argument is data.
* ND means: Node and Data. Data is void *, so it could be anything.
* @js NA
*/
class CC_DLL __CCCallFuncND : public CallFunc
{
@ -505,6 +506,7 @@ private:
@deprecated Please use CallFuncN instead.
@brief Calls a 'callback' with an object as the first argument. O means Object.
@since v0.99.5
@js NA
*/
class CC_DLL __CCCallFuncO : public CallFunc

View File

@ -160,12 +160,14 @@ public:
* @param action1 The first sequenceable action.
* @param args The va_list variable.
* @return An autoreleased Sequence object.
* @js NA
*/
static Sequence* createWithVariableList(FiniteTimeAction *action1, va_list args);
/** Creates the action.
* @param actionOne The first sequenceable action.
* @param actionTwo The second sequenceable action.
* @return An autoreleased Sequence object.
* @js NA
*/
static Sequence* createWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo);
@ -374,6 +376,7 @@ public:
* @param action1 The first sequenceable action.
* @param args The va_list variable.
* @return An autoreleased Spawn object.
* @js NA
*/
static Spawn* createWithVariableList(FiniteTimeAction *action1, va_list args);
@ -389,6 +392,7 @@ public:
* @param action1 The first spawned action.
* @param action2 THe second spawned action.
* @return An autoreleased Spawn object.
* @js NA
*/
static Spawn* createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2);
@ -1187,7 +1191,10 @@ public:
virtual void startWithTarget(Node *target) override;
virtual FadeIn* clone() const override;
virtual FadeTo* reverse(void) const override;
/**
* @js NA
*/
void setReverseAction(FadeTo* ac);
CC_CONSTRUCTOR_ACCESS:
@ -1218,7 +1225,10 @@ public:
virtual void startWithTarget(Node *target) override;
virtual FadeOut* clone() const override;
virtual FadeTo* reverse(void) const override;
/**
* @js NA
*/
void setReverseAction(FadeTo* ac);
CC_CONSTRUCTOR_ACCESS:

View File

@ -110,6 +110,7 @@ public:
*
* @param tag The actions' tag.
* @param target A certain target.
* @js NA
*/
void removeAllActionsByTag(int tag, Node *target);
@ -128,6 +129,7 @@ public:
*
* @param target A certain target.
* @return The numbers of actions that are running in a certain target.
* @js NA
*/
ssize_t getNumberOfRunningActionsInTarget(const Node *target) const;

View File

@ -41,7 +41,7 @@ class Texture2D;
class SpriteFrame;
/**
* @addtogroup sprite_nodes
* @addtogroup _2d
* @{
*/

View File

@ -40,7 +40,7 @@ NS_CC_BEGIN
class Animation;
/**
* @addtogroup sprite_nodes
* @addtogroup _2d
* @{
*/

View File

@ -36,7 +36,7 @@ THE SOFTWARE.
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @addtogroup _2d
* @{
*/

View File

@ -174,14 +174,24 @@ public:
//override
virtual void onEnter() override;
virtual void onExit() override;
/**
* Get the visiting camera , the visiting camera shall be set on Scene::render
*/
static const Camera* getVisitingCamera() { return _visitingCamera; }
/**
* Get the default camera of the current running scene.
*/
static Camera* getDefaultCamera();
CC_CONSTRUCTOR_ACCESS:
Camera();
~Camera();
/**
* Set the scene,this method shall not be invoke manually
*/
void setScene(Scene* scene);
/**set additional matrix for the projection matrix, it multiplys mat to projection matrix when called, used by WP8*/

View File

@ -34,51 +34,82 @@
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN
/**
* @addtogroup _2d
* @{
*/
/** ClippingNode is a subclass of Node.
It draws its content (childs) clipped using a stencil.
The stencil is an other Node that will not be drawn.
The clipping is done using the alpha part of the stencil (adjusted with an alphaThreshold).
* It draws its content (childs) clipped using a stencil.
* The stencil is an other Node that will not be drawn.
* The clipping is done using the alpha part of the stencil (adjusted with an alphaThreshold).
*/
class CC_DLL ClippingNode : public Node
{
public:
/** Creates and initializes a clipping node without a stencil.
*
* @return An autorelease ClippingNode.
*/
static ClippingNode* create();
/** Creates and initializes a clipping node with an other node as its stencil.
The stencil node will be retained.
* The stencil node will be retained.
* @param stencil The stencil node.
*/
static ClippingNode* create(Node *stencil);
/** The Node to use as a stencil to do the clipping.
The stencil node will be retained.
This default to nil.
* The stencil node will be retained.
* This default to nil.
*
* @return The stencil node.
*/
Node* getStencil() const;
/** Set the Node to use as a stencil to do the clipping.
*
* @param stencil The Node to use as a stencil to do the clipping.
*/
void setStencil(Node *stencil);
/** If stencil has no childre it will not be drawn.
If you have custom stencil-based node with stencil drawing mechanics other then children-based,
then this method should return true every time you wish stencil to be visited.
By default returns true if has any children attached.
*/
* If you have custom stencil-based node with stencil drawing mechanics other then children-based,
* then this method should return true every time you wish stencil to be visited.
* By default returns true if has any children attached.
*
* @return If you have custom stencil-based node with stencil drawing mechanics other then children-based,
* then this method should return true every time you wish stencil to be visited.
* By default returns true if has any children attached.
*/
virtual bool hasContent() const;
/** The alpha threshold.
The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
Should be a float between 0 and 1.
This default to 1 (so alpha test is disabled).
* The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
* Should be a float between 0 and 1.
* This default to 1 (so alpha test is disabled).
*
* @return The alpha threshold value,Should be a float between 0 and 1.
*/
GLfloat getAlphaThreshold() const;
/** Set the alpha threshold.
*
* @param alphaThreshold The alpha threshold.
*/
void setAlphaThreshold(GLfloat alphaThreshold);
/** Inverted. If this is set to true,
the stencil is inverted, so the content is drawn where the stencil is NOT drawn.
This default to false.
* the stencil is inverted, so the content is drawn where the stencil is NOT drawn.
* This default to false.
*
* @return If the clippingNode is Inverted, it will be return true.
*/
bool isInverted() const;
/** Set the ClippingNode whether or not invert.
*
* @param inverted A bool Type,to set the ClippingNode whether or not invert.
*/
void setInverted(bool inverted);
// Overrides
@ -162,7 +193,7 @@ protected:
private:
CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode);
};
/** @} */
NS_CC_END
#endif // __MISCNODE_CCCLIPPING_NODE_H__

View File

@ -38,59 +38,202 @@
NS_CC_BEGIN
/** DrawNode
Node that draws dots, segments and polygons.
Faster than the "drawing primitives" since they draws everything in one single batch.
@since v2.1
class PointArray;
/**
* @addtogroup _2d
* @{
*/
class PointArray;
/** @class DrawNode
* @brief Node that draws dots, segments and polygons.
* Faster than the "drawing primitives" since they draws everything in one single batch.
* @since v2.1
*/
class CC_DLL DrawNode : public Node
{
public:
/** creates and initialize a DrawNode node */
/** creates and initialize a DrawNode node.
*
* @return Return an autorelease object.
*/
static DrawNode* create();
/** Draw a point.
*
* @param point A Vec2 used to point.
* @param pointSize The point size.
* @param color The point color.
*/
void drawPoint(const Vec2& point, const float pointSize, const Color4F &color);
/** Draw a group point.
*
* @param position A Vec2 pointer.
* @param numberOfPoints The number of points.
* @param color The point color.
*/
void drawPoints(const Vec2 *position, unsigned int numberOfPoints, const Color4F &color);
/** Draw a group point.
*
* @param position A Vec2 pointer.
* @param numberOfPoints The number of points.
* @param pointSize The point size.
* @param color The point color.
*/
void drawPoints(const Vec2 *position, unsigned int numberOfPoints, const float pointSize, const Color4F &color);
/** Draw an line from origin to destination with color.
*
* @param origin The line origin.
* @param destination The line destination.
* @param color The line color.
*/
void drawLine(const Vec2 &origin, const Vec2 &destination, const Color4F &color);
/** Draws a rectangle given the origin and destination point measured in points.
* The origin and the destination can not have the same x and y coordinate.
*
* @param origin The rectangle origin.
* @param destination The rectangle destination.
* @param color The rectangle color.
*/
void drawRect(const Vec2 &origin, const Vec2 &destination, const Color4F &color);
/** Draws a polygon given a pointer to point coordinates and the number of vertices measured in points.
* The polygon can be closed or open.
*
* @param poli A pointer to point coordinates.
* @param numberOfPoints The number of vertices measured in points.
* @param closePolygon The polygon can be closed or open.
* @param color The polygon color.
*/
void drawPoly(const Vec2 *poli, unsigned int numberOfPoints, bool closePolygon, const Color4F &color);
/** Draws a circle given the center, radius and number of segments.
*
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param drawLineToCenter Whether or not draw the line from the origin to center.
* @param scaleX The scale value in x.
* @param scaleY The scale value in y.
* @param color Set the circle color.
*/
void drawCircle( const Vec2& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY, const Color4F &color);
/** Draws a circle given the center, radius and number of segments.
*
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param drawLineToCenter Whether or not draw the line from the origin to center.
* @param color Set the circle color.
*/
void drawCircle(const Vec2 &center, float radius, float angle, unsigned int segments, bool drawLineToCenter, const Color4F &color);
/** Draws a quad bezier path.
*
* @param origin The origin of the bezier path.
* @param control The control of the bezier path.
* @param destination The destination of the bezier path.
* @param segments The The number of segments.
* @param color Set the quad bezier color.
*/
void drawQuadBezier(const Vec2 &origin, const Vec2 &control, const Vec2 &destination, unsigned int segments, const Color4F &color);
/** draw a cubic bezier curve with color and number of segments */
/** Draw a cubic bezier curve with color and number of segments
*
* @param origin The origin of the bezier path.
* @param control1 The first control of the bezier path.
* @param control2 The second control of the bezier path.
* @param destination The destination of the bezier path.
* @param segments The The number of segments.
* @param color Set the cubic bezier color.
*/
void drawCubicBezier(const Vec2 &origin, const Vec2 &control1, const Vec2 &control2, const Vec2 &destination, unsigned int segments, const Color4F &color);
/** Draws a Cardinal Spline path.
*
* @param config A array point.
* @param tension The tension of the spline.
* @param segments The The number of segments.
* @param color Set the Spline color.
*/
void drawCardinalSpline(PointArray *config, float tension, unsigned int segments, const Color4F &color);
/** Draws a Catmull Rom path.
*
* @param points A point array of control point.
* @param segments The The number of segments.
* @param color The Catmull Rom color.
*/
void drawCatmullRom(PointArray *points, unsigned int segments, const Color4F &color);
/** draw a dot at a position, with a given radius and color */
/** draw a dot at a position, with a given radius and color.
*
* @param pos The dot center.
* @param radius The dot radius.
* @param color The dot color.
*/
void drawDot(const Vec2 &pos, float radius, const Color4F &color);
/** Draws a rectangle with 4 points.
*
* @param p1 The rectangle vertex point.
* @param p2 The rectangle vertex point.
* @param p3 The rectangle vertex point.
* @param p4 The rectangle vertex point.
* @param color The rectangle color.
*/
void drawRect(const Vec2 &p1, const Vec2 &p2, const Vec2 &p3, const Vec2& p4, const Color4F &color);
/** Draws a solid rectangle given the origin and destination point measured in points.
* The origin and the destination can not have the same x and y coordinate.
*
* @param origin The rectangle origin.
* @param destination The rectangle destination.
* @param color The rectangle color.
*/
void drawSolidRect(const Vec2 &origin, const Vec2 &destination, const Color4F &color);
/** Draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color.
*
* @param poli A solid polygon given a pointer to CGPoint coordinates.
* @param numberOfPoints The number of vertices measured in points.
* @param color The solid polygon color.
*/
void drawSolidPoly(const Vec2 *poli, unsigned int numberOfPoints, const Color4F &color);
/** Draws a solid circle given the center, radius and number of segments.
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param scaleX The scale value in x.
* @param scaleY The scale value in y.
* @param color The solid circle color.
*/
void drawSolidCircle(const Vec2& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY, const Color4F &color);
/** Draws a solid circle given the center, radius and number of segments.
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param color The solid circle color.
*/
void drawSolidCircle(const Vec2& center, float radius, float angle, unsigned int segments, const Color4F& color);
/** draw a segment with a radius and color */
/** draw a segment with a radius and color.
*
* @param from The segment origin.
* @param to The segment destination.
* @param radius The segment radius.
* @param color The segment color.
*/
void drawSegment(const Vec2 &from, const Vec2 &to, float radius, const Color4F &color);
/** draw a polygon with a fill color and line color
@ -99,23 +242,41 @@ public:
* In js: var drawPolygon(var Arrayofpoints, var fillColor, var width, var borderColor)
* In lua:local drawPolygon(local pointTable,local tableCount,local fillColor,local width,local borderColor)
* @endcode
* @param verts A pointer to point coordinates.
* @param count The number of verts measured in points.
* @param fillColor The color will fill in polygon.
* @param borderWidth The border of line width.
* @param borderColor The border of line color.
*/
void drawPolygon(const Vec2 *verts, int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor);
/** draw a triangle with color */
/** draw a triangle with color.
*
* @param p1 The triangle vertex point.
* @param p2 The triangle vertex point.
* @param p3 The triangle vertex point.
* @param color The triangle color.
*/
void drawTriangle(const Vec2 &p1, const Vec2 &p2, const Vec2 &p3, const Color4F &color);
/** draw a quadratic bezier curve with color and number of segments, use drawQuadBezier instead*/
/** draw a quadratic bezier curve with color and number of segments, use drawQuadBezier instead.
*
* @param from The origin of the bezier path.
* @param control The control of the bezier path.
* @param to The destination of the bezier path.
* @param segments The The number of segments.
* @param color The quadratic bezier color.
*/
CC_DEPRECATED_ATTRIBUTE void drawQuadraticBezier(const Vec2& from, const Vec2& control, const Vec2& to, unsigned int segments, const Color4F &color);
/** Clear the geometry in the node's buffer. */
void clear();
/**
/** Get the color mixed mode.
* @js NA
* @lua NA
*/
const BlendFunc& getBlendFunc() const;
/**
/** Set the color mixed mode.
* @code
* When this function bound into js or lua,the parameter will be changed
* In js: var setBlendFunc(var src, var dst)
@ -174,7 +335,7 @@ protected:
private:
CC_DISALLOW_COPY_AND_ASSIGN(DrawNode);
};
/** @} */
NS_CC_END
#endif // __CCDRAWNODES_CCDRAW_NODE_H__

View File

@ -70,7 +70,7 @@ THE SOFTWARE.
NS_CC_BEGIN
/**
* @addtogroup global
* @addtogroup _2d
* @{
*/
@ -78,91 +78,181 @@ class PointArray;
namespace DrawPrimitives
{
/** Initializes the drawing primitives */
/** Initializes the drawing primitives. */
CC_DEPRECATED_ATTRIBUTE void CC_DLL init();
/** Frees allocated resources by the drawing primitives */
/** Frees allocated resources by the drawing primitives. */
CC_DEPRECATED_ATTRIBUTE void CC_DLL free();
/** draws a point given x and y coordinate measured in points */
/** Draws a point given x and y coordinate measured in points
*
* @param point A Vec2 with a point given x and y coordinate.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawPoint(const Vec2& point);
/** draws an array of points.
@since v0.7.2
/** Draws an array of points.
*
* @param point A point coordinates.
* @param numberOfPoints The number of points.
* @since v0.7.2
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawPoints(const Vec2 *points, unsigned int numberOfPoints);
/** draws a line given the origin and destination point measured in points */
/** Draws a line given the origin and destination point measured in points
*
* @param origin A Vec2 Type point used to the line origin.
* @param destination A Vec2 Type point used to the line destination.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawLine(const Vec2& origin, const Vec2& destination);
/** draws a rectangle given the origin and destination point measured in points. */
/** Draws a rectangle given the origin and destination point measured in points.
* The origin and the destination can not have the same x and y coordinate.
*
* @param origin The rectangle origin.
* @param destination The rectangle destination.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawRect(Vec2 origin, Vec2 destination);
/** draws a solid rectangle given the origin and destination point measured in points.
@since 1.1
/** Draws a solid rectangle given the origin and destination point measured in points.
* The origin and the destination can not have the same x and y coordinate.
*
* @param origin The rectangle origin.
* @param destination The rectangle destination.
* @param color The rectangle color.
* @since 1.1
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawSolidRect(Vec2 origin, Vec2 destination, Color4F color);
/** draws a polygon given a pointer to point coordinates and the number of vertices measured in points.
The polygon can be closed or open
*/
/** Draws a polygon given a pointer to point coordinates and the number of vertices measured in points.
* The polygon can be closed or open.
*
* @param vertices A pointer to point coordinates.
* @param numOfVertices The number of vertices measured in points.
* @param closePolygon The polygon can be closed or open.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawPoly(const Vec2 *vertices, unsigned int numOfVertices, bool closePolygon);
/** draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color.
/** Draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color.
*
* @param poli A solid polygon given a pointer to CGPoint coordinates.
* @param numberOfPoints The number of vertices measured in points.
* @param color The solid polygon color.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawSolidPoly(const Vec2 *poli, unsigned int numberOfPoints, Color4F color);
/** draws a circle given the center, radius and number of segments. */
/** Draws a circle given the center, radius and number of segments.
*
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param drawLineToCenter Whether or not draw the line from the origin to center.
* @param scaleX The scale value in x.
* @param scaleY The scale value in y.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawCircle(const Vec2& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY);
/** Draws a circle given the center, radius and number of segments.
*
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param drawLineToCenter Whether or not draw the line from the origin to center.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawCircle(const Vec2& center, float radius, float angle, unsigned int segments, bool drawLineToCenter);
/** draws a solid circle given the center, radius and number of segments. */
/** Draws a solid circle given the center, radius and number of segments.
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
* @param scaleX The scale value in x.
* @param scaleY The scale value in y.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawSolidCircle(const Vec2& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY);
/** Draws a solid circle given the center, radius and number of segments.
* @param center The circle center point.
* @param radius The circle rotate of radius.
* @param angle The circle angel.
* @param segments The number of segments.
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawSolidCircle(const Vec2& center, float radius, float angle, unsigned int segments);
/** draws a quad bezier path
@warning This function could be pretty slow. Use it only for debugging purposes.
@since v0.8
/** Draws a quad bezier path.
*
* @param origin The origin of the bezier path.
* @param control The control of the bezier path.
* @param destination The destination of the bezier path.
* @param segments The The number of segments.
* @warning This function could be pretty slow. Use it only for debugging purposes.
* @since v0.8
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawQuadBezier(const Vec2& origin, const Vec2& control, const Vec2& destination, unsigned int segments);
/** draws a cubic bezier path
@warning This function could be pretty slow. Use it only for debugging purposes.
@since v0.8
/** Draws a cubic bezier path.
*
* @param origin The origin of the bezier path.
* @param control1 The first control of the bezier path.
* @param control2 The second control of the bezier path.
* @param destination The destination of the bezier path.
* @param segments The The number of segments.
* @warning This function could be pretty slow. Use it only for debugging purposes.
* @since v0.8
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawCubicBezier(const Vec2& origin, const Vec2& control1, const Vec2& control2, const Vec2& destination, unsigned int segments);
/** draws a Catmull Rom path.
@warning This function could be pretty slow. Use it only for debugging purposes.
@since v2.0
/** Draws a Catmull Rom path.
*
* @param arrayOfControlPoints A point array of control point.
* @param segments The The number of segments.
* @warning This function could be pretty slow. Use it only for debugging purposes.
* @since v2.0
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawCatmullRom(PointArray *arrayOfControlPoints, unsigned int segments);
/** draws a Cardinal Spline path.
@warning This function could be pretty slow. Use it only for debugging purposes.
@since v2.0
/** Draws a Cardinal Spline path.
*
* @param config A array point.
* @param tension The tension of the spline.
* @param segments The The number of segments.
* @warning This function could be pretty slow. Use it only for debugging purposes.
* @since v2.0
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL drawCardinalSpline(PointArray *config, float tension, unsigned int segments);
/** set the drawing color with 4 unsigned bytes
@since v2.0
/** Set the drawing color with 4 unsigned bytes.
*
* @param r The red color with a unsigned bytes.
* @param g The green color with a unsigned bytes.
* @param b The blue color with a unsigned bytes.
* @param a Alpha with a unsigned bytes.
* @since v2.0
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL setDrawColor4B(GLubyte r, GLubyte g, GLubyte b, GLubyte a);
/** set the drawing color with 4 floats
@since v2.0
/** Set the drawing color with 4 floats.
*
* @param r The red color with an floats.
* @param g The green color with an floats.
* @param b The blue color with an floats.
* @param a Alpha with an floats.
* @since v2.0
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL setDrawColor4F(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
/** set the point size in points. Default 1.
@since v2.0
/** Set the point size in points. Default 1.
*
* @param pointSize The point size with an float.
* @since v2.0
*/
CC_DEPRECATED_ATTRIBUTE void CC_DLL setPointSize(GLfloat pointSize);
};
// end of global group
/// @}
/** @} */
NS_CC_END

View File

@ -46,40 +46,45 @@ struct _ccCArray;
namespace experimental{
/**
* @addtogroup tilemap_parallax_nodes
* @addtogroup _2d
* @{
*/
/** @brief FastTMXLayer represents the TMX layer.
It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
The benefits of using Sprite objects as tiles are:
- tiles (Sprite) can be rotated/scaled/moved with a nice API
* It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
* If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
* The benefits of using Sprite objects as tiles are:
* - tiles (Sprite) can be rotated/scaled/moved with a nice API.
If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
* If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
* then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
* On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
* Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
glAlphaFunc( GL_GREATER, value )
* glAlphaFunc( GL_GREATER, value ).
"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
value, like 0.5.
For further information, please see the programming guide:
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
@since v3.2
*/
* "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
* The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
* value, like 0.5.
* For further information, please see the programming guide:
* http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
* @since v3.2
*/
class CC_DLL TMXLayer : public Node
{
public:
/** creates a FastTMXLayer with an tileset info, a layer info and a map info */
/** Creates a FastTMXLayer with an tileset info, a layer info and a map info.
*
* @param tilesetInfo An tileset info.
* @param layerInfo A layer info.
* @param mapInfo A map info.
* @return Reruen an autorelease object.
*/
static TMXLayer * create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/**
* @js ctor
@ -91,83 +96,170 @@ public:
*/
virtual ~TMXLayer();
/** returns the tile gid at a given tile coordinate. It also returns the tile flags.
/** Returns the tile gid at a given tile coordinate. It also returns the tile flags.
*
* @param tileCoordinate The tile coordinate.
* @param flags A TMXTileFlags.
* @return The tile gid at a given tile coordinate. It also returns the tile flags.
*/
int getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags = nullptr);
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
*/
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
* @param gid The gid value.
* @param tileCoordinate The tile coordinate.
*/
void setTileGID(int gid, const Vec2& tileCoordinate);
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
Use withFlags if the tile flags need to be changed as well
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
* Use withFlags if the tile flags need to be changed as well.
*
* @param gid A integer value,it will be sets the tile gid.
* @param tileCoordinate The tile coordinate.
* @param flags A TMXTileFlags.
*/
void setTileGID(int gid, const Vec2& tileCoordinate, TMXTileFlags flags);
/** removes a tile at given tile coordinate */
/** Removes a tile at given tile coordinate.
*
* @param tileCoordinate The tile Coordinate.
*/
void removeTileAt(const Vec2& tileCoordinate);
/** returns the position in points of a given tile coordinate */
/** Returns the position in points of a given tile coordinate.
*
* @param tileCoordinate The tile Coordinate.
* @return The position in points of a given tile coordinate.
*/
Vec2 getPositionAt(const Vec2& tileCoordinate);
/** return the value for the specific property name */
/** Return the value for the specific property name.
*
* @param propertyName The value for the specific property name.
* @return The value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
/** Creates the tiles */
/** Creates the tiles. */
void setupTiles();
/** Get the tile layer name.
*
* @return The tile layer name.
*/
inline const std::string& getLayerName(){ return _layerName; }
/** Set the tile layer name.
*
* @param layerName The new layer name.
*/
inline void setLayerName(const std::string& layerName){ _layerName = layerName; }
/** size of the layer in tiles */
/** Size of the layer in tiles.
*
* @return Size of the layer in tiles.
*/
inline const Size& getLayerSize() const { return _layerSize; };
/** Set the size of the layer in tiles.
*
* @param size The new size of the layer in tiles.
*/
inline void setLayerSize(const Size& size) { _layerSize = size; };
/** size of the map's tile (could be different from the tile's size) */
/** Size of the map's tile (could be different from the tile's size).
*
* @return Size of the map's tile (could be different from the tile's size).
*/
inline const Size& getMapTileSize() const { return _mapTileSize; };
/** Set the size of the map's tile.
*
* @param size The new size of the map's tile.
*/
inline void setMapTileSize(const Size& size) { _mapTileSize = size; };
/** pointer to the map of tiles
/** Pointer to the map of tiles.
* @js NA
* @lua NA
* @return The pointer to the map of tiles.
*/
const uint32_t* getTiles() const { return _tiles; };
/** Set the pointer to the map of tiles.
*
* @param tiles The pointer to the map of tiles.
*/
void setTiles(uint32_t* tiles) { _tiles = tiles; _quadsDirty = true;};
/** Tileset information for the layer */
/** Tileset information for the layer.
*
* @return Tileset information for the layer.
*/
inline TMXTilesetInfo* getTileSet() const { return _tileSet; };
/** Set the tileset information for the layer.
*
* @param info The new tileset information for the layer.
*/
inline void setTileSet(TMXTilesetInfo* info) {
CC_SAFE_RETAIN(info);
CC_SAFE_RELEASE(_tileSet);
_tileSet = info;
};
/** Layer orientation, which is the same as the map orientation */
/** Layer orientation, which is the same as the map orientation.
*
* @return Layer orientation, which is the same as the map orientation.
*/
inline int getLayerOrientation() const { return _layerOrientation; };
/** Set Layer orientation, which is the same as the map orientation.
*
* @param orientation Layer orientation, which is the same as the map orientation.
*/
inline void setLayerOrientation(int orientation) { _layerOrientation = orientation; };
/** properties from the layer. They can be added using Tiled */
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline const ValueMap& getProperties() const { return _properties; };
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline ValueMap& getProperties() { return _properties; };
/** Set the properties to the layer.
*
* @param properties The properties to the layer.
*/
inline void setProperties(const ValueMap& properties)
{
_properties = properties;
};
/** returns the tile (Sprite) at a given a tile coordinate.
The returned Sprite will be already added to the TMXLayer. Don't add it again.
The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- layer->removeChild(sprite, cleanup);
/** Returns the tile (Sprite) at a given a tile coordinate.
* The returned Sprite will be already added to the TMXLayer. Don't add it again.
* The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
* You can remove either by calling:
* - layer->removeChild(sprite, cleanup);
*
* @return Returns the tile (Sprite) at a given a tile coordinate.
*/
Sprite* getTileAt(const Vec2& tileCoordinate);
/** Set an sprite to the tile,with the tile coordinate and gid.
*
* @param sprite A Sprite.
* @param pos The tile coordinate.
* @param gid The tile gid.
*/
void setupTileSprite(Sprite* sprite, Vec2 pos, int gid);
//

View File

@ -39,100 +39,164 @@ class TMXMapInfo;
namespace experimental {
class TMXLayer;
/**
* @addtogroup _2d
* @{
*/
/** @brief FastTMXTiledMap knows how to parse and render a TMX map.
It adds support for the TMX tiled map format used by http://www.mapeditor.org
It supports isometric, hexagonal and orthogonal tiles.
It also supports object groups, objects, and properties.
* It adds support for the TMX tiled map format used by http://www.mapeditor.org.
* It supports isometric, hexagonal and orthogonal tiles.
* It also supports object groups, objects, and properties.
Features:
- Each tile will be treated as an Sprite
- The sprites are created on demand. They will be created only when you call "layer->tileAt(position)"
- Each tile can be rotated / moved / scaled / tinted / "opaqued", since each tile is a Sprite
- Tiles can be added/removed in runtime
- The z-order of the tiles can be modified in runtime
- Each tile has an anchorPoint of (0,0)
- The anchorPoint of the TMXTileMap is (0,0)
- The TMX layers will be added as a child
- The TMX layers will be aliased by default
- The tileset image will be loaded using the TextureCache
- Each tile will have a unique tag
- Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z
- Each object group will be treated as an MutableArray
- Object class which will contain all the properties in a dictionary
- Properties can be assigned to the Map, Layer, Object Group, and Object
* Features:
* - Each tile will be treated as an Sprite.
* - The sprites are created on demand. They will be created only when you call "layer->tileAt(position)".
* - Each tile can be rotated / moved / scaled / tinted / "opaqued", since each tile is a Sprite.
* - Tiles can be added/removed in runtime.
* - The z-order of the tiles can be modified in runtime.
* - Each tile has an anchorPoint of (0,0).
* - The anchorPoint of the TMXTileMap is (0,0).
* - The TMX layers will be added as a child.
* - The TMX layers will be aliased by default.
* - The tileset image will be loaded using the TextureCache.
* - Each tile will have a unique tag.
* - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z.
* - Each object group will be treated as an MutableArray.
* - Object class which will contain all the properties in a dictionary.
* - Properties can be assigned to the Map, Layer, Object Group, and Object.
Limitations:
- It only supports one tileset per layer.
- Embedded images are not supported
- It only supports the XML format (the JSON format is not supported)
* Limitations:
* - It only supports one tileset per layer.
* - Embedded images are not supported.
* - It only supports the XML format (the JSON format is not supported).
Technical description:
Each layer is created using an FastTMXLayer (subclass of SpriteBatchNode). If you have 5 layers, then 5 FastTMXLayer will be created,
unless the layer visibility is off. In that case, the layer won't be created at all.
You can obtain the layers (FastTMXLayer objects) at runtime by:
- map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
- map->getLayer(name_of_the_layer);
* Technical description:
* Each layer is created using an FastTMXLayer (subclass of SpriteBatchNode). If you have 5 layers, then 5 FastTMXLayer will be created,
* unless the layer visibility is off. In that case, the layer won't be created at all.
* You can obtain the layers (FastTMXLayer objects) at runtime by:
* - map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
* - map->getLayer(name_of_the_layer);
Each object group is created using a TMXObjectGroup which is a subclass of MutableArray.
You can obtain the object groups at runtime by:
- map->getObjectGroup(name_of_the_object_group);
* Each object group is created using a TMXObjectGroup which is a subclass of MutableArray.
* You can obtain the object groups at runtime by:
* - map->getObjectGroup(name_of_the_object_group);
Each object is a TMXObject.
* Each object is a TMXObject.
Each property is stored as a key-value pair in an MutableDictionary.
You can obtain the properties at runtime by:
* Each property is stored as a key-value pair in an MutableDictionary.
* You can obtain the properties at runtime by:
map->getProperty(name_of_the_property);
layer->getProperty(name_of_the_property);
objectGroup->getProperty(name_of_the_property);
object->getProperty(name_of_the_property);
* map->getProperty(name_of_the_property);
* layer->getProperty(name_of_the_property);
* objectGroup->getProperty(name_of_the_property);
* object->getProperty(name_of_the_property);
@since v3.2
*/
* @since v3.2
*/
class CC_DLL TMXTiledMap : public Node
{
public:
/** creates a TMX Tiled Map with a TMX file.*/
/** Creates a TMX Tiled Map with a TMX file.
*
* @return An autorelease object.
*/
static TMXTiledMap* create(const std::string& tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */
/** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources.
*
* @param tmxString A TMX formatted XML string.
* @param resourcePath A path to TMX resources.
* @return An autorelease object.
*/
static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** return the FastTMXLayer for the specific layer */
/** Return the FastTMXLayer for the specific layer.
*
* @return Return the FastTMXLayer for the specific layer.
*/
TMXLayer* getLayer(const std::string& layerName) const;
/** return the TMXObjectGroup for the specific group */
/** Return the TMXObjectGroup for the specific group.
*
* @return Return the TMXObjectGroup for the specific group.
*/
TMXObjectGroup* getObjectGroup(const std::string& groupName) const;
/** return the value for the specific property name */
/** Return the value for the specific property name.
*
* @return Return the value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
/** return properties dictionary for tile GID */
/** Return properties dictionary for tile GID.
*
* @return Return properties dictionary for tile GID.
*/
Value getPropertiesForGID(int GID) const;
/** the map's size property measured in tiles */
/** The map's size property measured in tiles.
*
* @return The map's size property measured in tiles.
*/
inline const Size& getMapSize() const { return _mapSize; };
/** Set the map's size property measured in tiles.
*
* @param mapSize The map's size property measured in tiles.
*/
inline void setMapSize(const Size& mapSize) { _mapSize = mapSize; };
/** the tiles's size property measured in pixels */
/** The tiles's size property measured in pixels.
*
* @return The tiles's size property measured in pixels.
*/
inline const Size& getTileSize() const { return _tileSize; };
/** Set the tiles's size property measured in pixels.
*
* @param tileSize The tiles's size property measured in pixels.
*/
inline void setTileSize(const Size& tileSize) { _tileSize = tileSize; };
/** map orientation */
/** Get map orientation.
*
* @return The map orientation.
*/
inline int getMapOrientation() const { return _mapOrientation; };
/** Set map orientation.
*
* @param mapOrientation The map orientation.
*/
inline void setMapOrientation(int mapOrientation) { _mapOrientation = mapOrientation; };
/** object groups */
/** Get object groups.
*
* @return Object groups.
*/
inline const Vector<TMXObjectGroup*>& getObjectGroups() const { return _objectGroups; };
inline Vector<TMXObjectGroup*>& getObjectGroups() { return _objectGroups; };
/** Set object groups.
*
* @param groups An object groups.
*/
inline void setObjectGroups(const Vector<TMXObjectGroup*>& groups) {
_objectGroups = groups;
};
/** properties */
/** Get properties.
*
* @return Properties.
*/
inline const ValueMap& getProperties() const { return _properties; };
/** Set properties.
*
* @param properties An ValueMap Properties.
*/
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
@ -180,7 +244,7 @@ private:
};
// end of tilemap_parallax_nodes group
/// @}
/** @} */
} //end of namespace experimental

View File

@ -52,7 +52,8 @@ class Touch;
//
// Layer
//
/** @brief Layer is a subclass of Node that implements the TouchEventsDelegate protocol.
/** @class Layer
* @brief Layer is a subclass of Node that implements the TouchEventsDelegate protocol.
All features from Node are valid, plus the following new features:
- It can receive iPhone Touches
@ -61,7 +62,10 @@ All features from Node are valid, plus the following new features:
class CC_DLL Layer : public Node
{
public:
/** creates a fullscreen black layer */
/** Creates a fullscreen black layer.
*
* @return An autoreleased Layer object.
*/
static Layer *create();
// Deprecated touch callbacks.
@ -78,21 +82,78 @@ public:
/* Callback function should not be deprecated, it will generate lots of warnings.
Since 'setTouchEnabled' was deprecated, it will make warnings if developer overrides onTouchXXX and invokes setTouchEnabled(true) instead of using EventDispatcher::addEventListenerWithXXX.
*/
virtual bool onTouchBegan(Touch *touch, Event *unused_event);
virtual void onTouchMoved(Touch *touch, Event *unused_event);
virtual void onTouchEnded(Touch *touch, Event *unused_event);
/** Callback function for touch began.
*
* @param touch Touch infomation.
* @param unused_event Event information.
* @return if return false, onTouchMoved, onTouchEnded, onTouchCancelled will never called.
* @js NA
*/
virtual bool onTouchBegan(Touch *touch, Event *unused_event);
/** Callback function for touch moved.
*
* @param touch Touch infomation.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchMoved(Touch *touch, Event *unused_event);
/** Callback function for touch ended.
*
* @param touch Touch infomation.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchEnded(Touch *touch, Event *unused_event);
/** Callback function for touch cancelled.
*
* @param touch Touch infomation.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchCancelled(Touch *touch, Event *unused_event);
/** Callback function for multiple touches began.
*
* @param touches Touches information.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event);
/** Callback function for multiple touches moved.
*
* @param touches Touches information.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event);
/** Callback function for multiple touches ended.
*
* @param touches Touches information.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event);
/** Callback function for multiple touches cancelled.
*
* @param touches Touches information.
* @param unused_event Event information.
* @js NA
*/
virtual void onTouchesCancelled(const std::vector<Touch*>&touches, Event *unused_event);
/** @deprecated Please override onAcceleration */
/**
@deprecated Please override onAcceleration
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(Acceleration* accelerationValue) final {};
/* Callback function should not be deprecated, it will generate lots of warnings.
Since 'setAccelerometerEnabled' was deprecated, it will make warnings if developer overrides onAcceleration and invokes setAccelerometerEnabled(true) instead of using EventDispatcher::addEventListenerWithXXX.
*/
/** Callback funtion for acceleration.
* @param acc Acceleration information.
* @param unused_event Event information.
* @js NA
*/
virtual void onAcceleration(Acceleration* acc, Event* unused_event);
/** If isTouchEnabled, this method is called onEnter. Override it to change the
@ -104,6 +165,7 @@ public:
TouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,INT_MIN+1,true);
}
@since v0.8.0
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void registerWithTouchDispatcher() final {};
@ -111,6 +173,7 @@ public:
You can enable / disable touch events with this property.
Only the touches of this node will be affected. This "method" is not propagated to it's children.
@since v0.8.1
@js NA
*/
CC_DEPRECATED_ATTRIBUTE bool isTouchEnabled() const;
CC_DEPRECATED_ATTRIBUTE void setTouchEnabled(bool value);
@ -118,13 +181,17 @@ public:
CC_DEPRECATED_ATTRIBUTE virtual void setTouchMode(Touch::DispatchMode mode);
CC_DEPRECATED_ATTRIBUTE virtual Touch::DispatchMode getTouchMode() const;
/** swallowsTouches of the touch events. Default is true */
/**
swallowsTouches of the touch events. Default is true
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void setSwallowsTouches(bool swallowsTouches);
CC_DEPRECATED_ATTRIBUTE virtual bool isSwallowsTouches() const;
/** whether or not it will receive Accelerometer events
You can enable / disable accelerometer events with this property.
@since v0.8.1
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual bool isAccelerometerEnabled() const;
CC_DEPRECATED_ATTRIBUTE virtual void setAccelerometerEnabled(bool value);
@ -133,27 +200,47 @@ public:
/** whether or not it will receive keyboard or keypad events
You can enable / disable accelerometer events with this property.
it's new in cocos2d-x
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual bool isKeyboardEnabled() const;
CC_DEPRECATED_ATTRIBUTE virtual void setKeyboardEnabled(bool value);
/** Please use onKeyPressed instead. */
/**
Please use onKeyPressed instead.
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void keyPressed(int keyCode) final {};
/** Please use onKeyReleased instead. */
/**
Please use onKeyReleased instead.
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void keyReleased(int keyCode) final {};
/* Callback function should not be deprecated, it will generate lots of warnings.
Since 'setKeyboardEnabled' was deprecated, it will make warnings if developer overrides onKeyXXX and invokes setKeyboardEnabled(true) instead of using EventDispatcher::addEventListenerWithXXX.
*/
/** Callback function for key pressed.
* @param keyCode KeyCode information.
* @param event Event information.
* @js NA
*/
virtual void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event);
/** Callback function for key released.
* @param keyCode KeyCode information.
* @param event Event information.
* @js NA
*/
virtual void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);
CC_DEPRECATED_ATTRIBUTE virtual bool isKeypadEnabled() const final { return _keyboardEnabled; }
CC_DEPRECATED_ATTRIBUTE virtual void setKeypadEnabled(bool value);
/** @deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead. */
/**
@deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead.
@js NA
*/
CC_DEPRECATED_ATTRIBUTE virtual void keyBackClicked() final {};
CC_DEPRECATED_ATTRIBUTE virtual void keyMenuClicked() final {};
@ -190,12 +277,14 @@ private:
};
/** LayerRGBA is a subclass of Layer that implements the RGBAProtocol protocol using a solid color as the background.
/** @class __LayerRGBA
* @brief LayerRGBA is a subclass of Layer that implements the RGBAProtocol protocol using a solid color as the background.
All features from Layer are valid, plus the following new features that propagate into children that conform to the RGBAProtocol:
- opacity
- RGB colors
@since 2.1
@js NA
*/
class CC_DLL __LayerRGBA : public Layer, public __RGBAProtocol
{
@ -234,7 +323,8 @@ private:
//
// LayerColor
//
/** @brief LayerColor is a subclass of Layer that implements the RGBAProtocol protocol.
/** @class LayerColor
* @brief LayerColor is a subclass of Layer that implements the RGBAProtocol protocol.
All features from Layer are valid, plus the following new features:
- opacity
@ -243,18 +333,40 @@ All features from Layer are valid, plus the following new features:
class CC_DLL LayerColor : public Layer, public BlendProtocol
{
public:
/** creates a fullscreen black layer */
/** Creates a fullscreen black layer.
*
* @return An autoreleased LayerColor object.
*/
static LayerColor* create();
/** creates a Layer with color, width and height in Points */
/** Creates a Layer with color, width and height in Points.
*
* @param color The color of layer.
* @param width The width of layer.
* @param height The height of layer.
* @return An autoreleased LayerColor object.
*/
static LayerColor * create(const Color4B& color, GLfloat width, GLfloat height);
/** creates a Layer with color. Width and height are the window size. */
/** Creates a Layer with color. Width and height are the window size.
*
* @param color The color of layer.
* @return An autoreleased LayerColor object.
*/
static LayerColor * create(const Color4B& color);
/** change width in Points*/
/** Change width in Points.
*
* @param w The width of layer.
*/
void changeWidth(GLfloat w);
/** change height in Points*/
/** Change height in Points.
*
* @param h The height of layer.
*/
void changeHeight(GLfloat h);
/** change width and height in Points
/** Change width and height in Points.
*
* @param w The width of layer.
* @param h The Height of layer.
@since v0.8
*/
void changeWidthAndHeight(GLfloat w ,GLfloat h);
@ -267,7 +379,6 @@ public:
virtual void setContentSize(const Size & var) override;
/** BlendFunction. Conforms to BlendProtocol protocol */
/**
* @js NA
* @lua NA
*/
virtual const BlendFunc& getBlendFunc() const override;
@ -308,7 +419,8 @@ private:
//
// LayerGradient
//
/** @brief LayerGradient is a subclass of LayerColor that draws gradients across the background.
/** @class LayerGradient
* @brief LayerGradient is a subclass of LayerColor that draws gradients across the background.
All features from LayerColor are valid, plus the following new features:
- direction
@ -330,46 +442,95 @@ If ' compressedInterpolation' is enabled (default mode) you will see both the st
class CC_DLL LayerGradient : public LayerColor
{
public:
/** Creates a fullscreen black layer */
/** Creates a fullscreen black layer.
*
* @return An autoreleased LayerGradient object.
*/
static LayerGradient* create();
/** Creates a full-screen Layer with a gradient between start and end. */
/** Creates a full-screen Layer with a gradient between start and end.
*
* @param start The start color.
* @param end The end color.
* @return An autoreleased LayerGradient object.
*/
static LayerGradient* create(const Color4B& start, const Color4B& end);
/** Creates a full-screen Layer with a gradient between start and end in the direction of v. */
/** Creates a full-screen Layer with a gradient between start and end in the direction of v.
*
* @param start The start color.
* @param end The end color.
* @param v The direction of gradient color.
* @return An autoreleased LayerGradient object.
*/
static LayerGradient* create(const Color4B& start, const Color4B& end, const Vec2& v);
/** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors
Default: true
/** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors.
Default: true.
*
* @param compressedInterpolation The interpolation will be compressed if true.
*/
void setCompressedInterpolation(bool compressedInterpolation);
/** Get the compressedInterpolation
*
* @return The interpolation will be compressed if true.
*/
bool isCompressedInterpolation() const;
/** Sets the start color of the gradient */
/** Sets the start color of the gradient.
*
* @param startColor The start color.
*/
void setStartColor( const Color3B& startColor );
/** Returns the start color of the gradient */
/** Returns the start color of the gradient.
*
* @return The start color.
*/
const Color3B& getStartColor() const;
/** Sets the end color of the gradient */
/** Sets the end color of the gradient.
*
* @param endColor The end color.
*/
void setEndColor( const Color3B& endColor );
/** Returns the end color of the gradient */
/** Returns the end color of the gradient.
*
* @return The end color.
*/
const Color3B& getEndColor() const;
/** Returns the start opacity of the gradient */
/** Returns the start opacity of the gradient.
*
* @param startOpacity The start opacity, from 0 to 255.
*/
void setStartOpacity( GLubyte startOpacity );
/** Returns the start opacity of the gradient */
/** Returns the start opacity of the gradient.
*
* @return The start opacity.
*/
GLubyte getStartOpacity() const;
/** Returns the end opacity of the gradient */
/** Returns the end opacity of the gradient.
*
* @param endOpacity The end opacity, from 0 to 255.
*/
void setEndOpacity( GLubyte endOpacity );
/** Returns the end opacity of the gradient */
/** Returns the end opacity of the gradient.
*
* @return The end opacity.
*/
GLubyte getEndOpacity() const;
/** Sets the directional vector that will be used for the gradient.
The default value is vertical direction (0,-1).
*
* @param alongVector The direction of gradient.
*/
void setVector(const Vec2& alongVector);
/** Returns the directional vector used for the gradient */
/** Returns the directional vector used for the gradient.
*
* @return The direction of gradient.
*/
const Vec2& getVector() const;
virtual std::string getDescription() const override;
@ -403,7 +564,8 @@ protected:
};
/** @brief MultipleLayer is a Layer with the ability to multiplex it's children.
/** @class LayerMultiplex
* @brief MultipleLayer is a Layer with the ability to multiplex it's children.
Features:
- It supports one or more children
- Only one children will be active a time
@ -411,19 +573,23 @@ Features:
class CC_DLL LayerMultiplex : public Layer
{
public:
/** creates and initializes a LayerMultiplex object
* @js NA
/** Creates and initializes a LayerMultiplex object.
* @lua NA
*
* @return An autoreleased LayerMultiplex object.
*/
static LayerMultiplex* create();
/** creates a LayerMultiplex with an array of layers.
/** Creates a LayerMultiplex with an array of layers.
@since v2.1
* @js NA
*
* @param arrayOfLayers An array of layers.
* @return An autoreleased LayerMultiplex object.
*/
static LayerMultiplex* createWithArray(const Vector<Layer*>& arrayOfLayers);
/** creates a LayerMultiplex with one or more layers using a variable argument list.
/** Creates a LayerMultiplex with one or more layers using a variable argument list.
* @code
* When this function bound to lua or js,the input params are changed.
* In js:var create(...)
@ -450,24 +616,35 @@ public:
static LayerMultiplex * create(Layer* layer, ... );
#endif
/**
* lua script can not init with undetermined number of variables
/** Creates a LayerMultiplex with one layer.
* Lua script can not init with undetermined number of variables
* so add these functions to be used with lua.
* @js NA
* @lua NA
*
* @param layer A certain layer.
* @return An autoreleased LayerMultiplex object.
*/
static LayerMultiplex * createWithLayer(Layer* layer);
/** Add a certain layer to LayerMultiplex.
*
* @param layer A layer need to be added to the LayerMultiplex.
*/
void addLayer(Layer* layer);
/** switches to a certain layer indexed by n.
/** Switches to a certain layer indexed by n.
The current (old) layer will be removed from it's parent with 'cleanup=true'.
*
* @param n The layer indexed by n will display.
*/
void switchTo(int n);
/** release the current layer and switches to another layer indexed by n.
The current (old) layer will be removed from it's parent with 'cleanup=true'.
*/
*
* @param n The layer indexed by n will display.
*/
void switchToAndReleaseMe(int n);
virtual std::string getDescription() const override;

View File

@ -57,11 +57,17 @@ enum class LightFlag
LIGHT15 = 1 << 15,
};
/**
@js NA
*/
class CC_DLL BaseLight : public Node
{
public:
//get light type
/**
* Get the light type,light type MUST be one of LightType::DIRECTIONAL ,
* LightType::POINT, LightType::SPOT, LightType::AMBIENT.
*/
virtual LightType getLightType() const = 0;
/** intensity getter and setter */
@ -95,6 +101,9 @@ protected:
bool _enabled;
};
/**
@js NA
*/
class CC_DLL DirectionLight : public BaseLight
{
public:
@ -133,6 +142,9 @@ CC_CONSTRUCTOR_ACCESS:
};
/**
@js NA
*/
class CC_DLL PointLight : public BaseLight
{
public:
@ -161,6 +173,9 @@ protected:
float _range;
};
/**
@js NA
*/
class CC_DLL SpotLight : public BaseLight
{
public:
@ -252,6 +267,9 @@ protected:
float _cosOuterAngle;
};
/**
@js NA
*/
class CC_DLL AmbientLight : public BaseLight
{
public:

View File

@ -39,29 +39,64 @@ class Texture2D;
* @{
*/
/** MotionStreak.
Creates a trailing path.
/** @class MotionStreak.
* @brief Creates a trailing path.
*/
class CC_DLL MotionStreak : public Node, public TextureProtocol
{
public:
/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename */
/** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename.
*
* @param fade The fade time, in seconds.
* @param minSeg The minimum segments.
* @param stroke The width of stroke.
* @param color The color of stroke.
* @param path The texture file name of stoke.
* @return An autoreleased MotionStreak object.
*/
static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path);
/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */
/** Creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture.
*
* @param fade The fade time, in seconds.
* @param minSeg The minimum segments.
* @param stroke The width of stroke.
* @param color The color of stroke.
* @param texture The texture name of stoke.
* @return An autoreleased MotionStreak object.
*/
static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);
/** color used for the tint */
/** Color used for the tint.
*
* @param colors The color used for the tint.
*/
void tintWithColor(const Color3B& colors);
/** Remove all living segments of the ribbon */
/** Remove all living segments of the ribbon.
*/
void reset();
/** When fast mode is enabled, new points are added faster but with lower precision */
/** When fast mode is enabled, new points are added faster but with lower precision.
*
* @return True if fast mode is enabled.
*/
inline bool isFastMode() const { return _fastMode; }
/** Sets fast mode or not.
*
* @param bFastMode True if enabled fast mode.
*/
inline void setFastMode(bool bFastMode) { _fastMode = bFastMode; }
/** Is the starting position initialized or not.
*
* @return True if the starting position is initialized.
*/
inline bool isStartingPositionInitialized() const { return _startingPositionInitialized; }
inline void setStartingPositionInitialized(bool bStartingPositionInitialized)
/** Sets the starting position initialized or not.
*
* @param bStartingPositionInitialized True if initialized the starting position.
*/
inline void setStartingPositionInitialized(bool bStartingPositionInitialized)
{
_startingPositionInitialized = bStartingPositionInitialized;
}

File diff suppressed because it is too large Load Diff

View File

@ -32,25 +32,45 @@
NS_CC_BEGIN
class GridBase;
/**
* @addtogroup _2d
* @{
*/
/**
* @brief Base class for Grid Node.
*/
class CC_DLL NodeGrid : public Node
{
public:
/** Create a Grid Node.
*
* @return An autorelease Grid Node.
*/
static NodeGrid* create();
/** Get a Grid Node.
*
* @return Return a GridBase.
*/
GridBase* getGrid() { return _nodeGrid; }
/**
* @js NA
*/
* @js NA
*/
const GridBase* getGrid() const { return _nodeGrid; }
/**
* Changes a grid object that is used when applying effects
* Changes a grid object that is used when applying effects.
*
* @param grid A Grid object that is used when applying effects
* @param grid A Grid object that is used when applying effects.
*/
void setGrid(GridBase *grid);
/** Set the Grid Target.
*
* @param target A Node is used to set the Grid Target.
*/
void setTarget(Node *target);
// overrides
@ -73,6 +93,7 @@ protected:
private:
CC_DISALLOW_COPY_AND_ASSIGN(NodeGrid);
};
/** @} */
NS_CC_END
#endif

View File

@ -39,7 +39,8 @@ struct _ccArray;
* @{
*/
/** @brief ParallaxNode: A node that simulates a parallax scroller
/** @class ParallaxNode
* @brief ParallaxNode: A node that simulates a parallax scroller
The children will be moved faster / slower than the parent according the the parallax ratio.
@ -47,17 +48,33 @@ The children will be moved faster / slower than the parent according the the par
class CC_DLL ParallaxNode : public Node
{
public:
// Create a Parallax node
/** Create a Parallax node.
*
* @return An autoreleased ParallaxNode object.
*/
static ParallaxNode * create();
// prevents compiler warning: "Included function hides overloaded virtual functions"
using Node::addChild;
/** Adds a child to the container with a local z-order, parallax ratio and position offset.
*
* @param child A child node.
* @param z Z order for drawing priority.
* @param parallaxRatio A given parallax ratio.
* @param positionOffset A given position offset.
*/
void addChild(Node * child, int z, const Vec2& parallaxRatio, const Vec2& positionOffset);
/** Sets an array of layers for the Parallax node */
/** Sets an array of layers for the Parallax node.
*
* @param parallaxArray An array of layers for the Parallax node.
*/
void setParallaxArray( struct _ccArray *parallaxArray) { _parallaxArray = parallaxArray; }
/** Returns the array of layers of the Parallax node */
/** Returns the array of layers of the Parallax node.
*
* @return An array of layers for the Parallax node.
*/
struct _ccArray* getParallaxArray() { return _parallaxArray; }
const struct _ccArray* getParallaxArray() const { return _parallaxArray; }

View File

@ -47,7 +47,8 @@ class ParticleSystem;
#define kParticleDefaultCapacity 500
/** ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
/** @class ParticleBatchNode
* @brief ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
* (often known as "batch draw").
*
* A ParticleBatchNode can reference one and only one texture (one image file, one texture atlas).
@ -69,25 +70,53 @@ class ParticleSystem;
class CC_DLL ParticleBatchNode : public Node, public TextureProtocol
{
public:
/** initializes the particle system with Texture2D, a capacity of particles, which particle system to use */
/** Create the particle system with Texture2D, a capacity of particles, which particle system to use.
*
* @param tex A given texture.
* @param capacity A capacity of particles.
* @return An autoreleased ParticleBatchNode object.
*/
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 */
/** Create 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.
*
* @param fileImage A given file name.
* @param capacity A capacity of particles.
* @return An autoreleased ParticleBatchNode object.
*/
static ParticleBatchNode* create(const std::string& fileImage, int capacity = kParticleDefaultCapacity);
/** Inserts a child into the ParticleBatchNode */
/** Inserts a child into the ParticleBatchNode.
*
* @param system A given particle system.
* @param index The insert index.
*/
void insertChild(ParticleSystem* system, int index);
/** Remove a child of the ParticleBatchNode.
*
* @param index The index of the child.
* @param doCleanup True if all actions and callbacks on this node should be removed, false otherwise.
*/
void removeChildAtIndex(int index, bool doCleanup);
void removeAllChildrenWithCleanup(bool doCleanup) override;
/** disables a particle by inserting a 0'd quad into the texture atlas */
/** Disables a particle by inserting a 0'd quad into the texture atlas.
*
* @param particleIndex The index of the particle.
*/
void disableParticle(int particleIndex);
/** Gets the texture atlas used for drawing the quads */
/** Gets the texture atlas used for drawing the quads.
*
* @return The texture atlas used for drawing the quads.
*/
inline TextureAtlas* getTextureAtlas() const { return _textureAtlas; };
/** Sets the texture atlas used for drawing the quads */
/** Sets the texture atlas used for drawing the quads.
*
* @param atlas The texture atlas used for drawing the quads.
*/
inline void setTextureAtlas(TextureAtlas* atlas) { _textureAtlas = atlas; };
// Overrides

View File

@ -36,11 +36,22 @@ NS_CC_BEGIN
* @{
*/
//! @brief A fire particle system
/** @class ParticleFire
* @brief A fire particle system.
*/
class CC_DLL ParticleFire : public ParticleSystemQuad
{
public:
/** Create a fire particle system.
*
* @return An autoreleased ParticleFire object.
*/
static ParticleFire* create();
/** Create a fire particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleFire object.
*/
static ParticleFire* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -61,11 +72,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleFire);
};
//! @brief A fireworks particle system
/** @class ParticleFireworks
* @brief A fireworks particle system.
*/
class CC_DLL ParticleFireworks : public ParticleSystemQuad
{
public:
/** Create a fireworks particle system.
*
* @return An autoreleased ParticleFireworks object.
*/
static ParticleFireworks* create();
/** Create a fireworks particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleFireworks object.
*/
static ParticleFireworks* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -87,11 +109,22 @@ private:
};
//! @brief A sun particle system
/** @class ParticleSun
* @brief A sun particle system.
*/
class CC_DLL ParticleSun : public ParticleSystemQuad
{
public:
/** Create a sun particle system.
*
* @return An autoreleased ParticleSun object.
*/
static ParticleSun* create();
/** Create a sun particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSun object.
*/
static ParticleSun* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -113,11 +146,22 @@ private:
};
//! @brief A galaxy particle system
/** @class ParticleGalaxy
* @brief A galaxy particle system.
*/
class CC_DLL ParticleGalaxy : public ParticleSystemQuad
{
public:
/** Create a galaxy particle system.
*
* @return An autoreleased ParticleGalaxy object.
*/
static ParticleGalaxy* create();
/** Create a galaxy particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleGalaxy object.
*/
static ParticleGalaxy* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -139,11 +183,22 @@ private:
};
//! @brief A flower particle system
/** @class ParticleFlower
* @brief A flower particle system.
*/
class CC_DLL ParticleFlower : public ParticleSystemQuad
{
public:
/** Create a flower particle system.
*
* @return An autoreleased ParticleFlower object.
*/
static ParticleFlower* create();
/** Create a flower particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleFlower object.
*/
static ParticleFlower* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -164,11 +219,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleFlower);
};
//! @brief A meteor particle system
/** @class ParticleMeteor
* @brief A meteor particle system.
*/
class CC_DLL ParticleMeteor : public ParticleSystemQuad
{
public:
/** Create a meteor particle system.
*
* @return An autoreleased ParticleMeteor object.
*/
static ParticleMeteor * create();
/** Create a meteor particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleMeteor object.
*/
static ParticleMeteor* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -189,11 +255,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleMeteor);
};
//! @brief An spiral particle system
/** @class ParticleSpiral
* @brief An spiral particle system.
*/
class CC_DLL ParticleSpiral : public ParticleSystemQuad
{
public:
/** Create a spiral particle system.
*
* @return An autoreleased ParticleSpiral object.
*/
static ParticleSpiral* create();
/** Create a spiral particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSpiral object.
*/
static ParticleSpiral* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -215,11 +292,22 @@ private:
};
//! @brief An explosion particle system
/** @class ParticleExplosion
* @brief An explosion particle system.
*/
class CC_DLL ParticleExplosion : public ParticleSystemQuad
{
public:
/** Create a explosion particle system.
*
* @return An autoreleased ParticleExplosion object.
*/
static ParticleExplosion* create();
/** Create a explosion particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleExplosion object.
*/
static ParticleExplosion* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -240,11 +328,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleExplosion);
};
//! @brief An smoke particle system
/** @class ParticleSmoke
* @brief An smoke particle system.
*/
class CC_DLL ParticleSmoke : public ParticleSystemQuad
{
public:
/** Create a smoke particle system.
*
* @return An autoreleased ParticleSmoke object.
*/
static ParticleSmoke* create();
/** Create a smoke particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSmoke object.
*/
static ParticleSmoke* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -265,11 +364,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleSmoke);
};
//! @brief An snow particle system
/** @class ParticleSnow
* @brief An snow particle system.
*/
class CC_DLL ParticleSnow : public ParticleSystemQuad
{
public:
/** Create a snow particle system.
*
* @return An autoreleased ParticleSnow object.
*/
static ParticleSnow* create();
/** Create a snow particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSnow object.
*/
static ParticleSnow* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:
@ -290,11 +400,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(ParticleSnow);
};
//! @brief A rain particle system
/** @class ParticleRain
* @brief A rain particle system.
*/
class CC_DLL ParticleRain : public ParticleSystemQuad
{
public:
/** Create a rain particle system.
*
* @return An autoreleased ParticleRain object.
*/
static ParticleRain* create();
/** Create a rain particle system withe a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleRain object.
*/
static ParticleRain* createWithTotalParticles(int numberOfParticles);
CC_CONSTRUCTOR_ACCESS:

View File

@ -40,8 +40,8 @@ NS_CC_BEGIN
class ParticleBatchNode;
/**
Structure that contains the values of each particle
/** @struct sParticle
Structure that contains the values of each particle.
*/
typedef struct sParticle {
Vec2 pos;
@ -60,14 +60,18 @@ typedef struct sParticle {
unsigned int atlasIndex;
//! Mode A: gravity, direction, radial accel, tangential accel
/** @struct modeA
Mode A: gravity, direction, radial accel, tangential accel.
*/
struct {
Vec2 dir;
float radialAccel;
float tangentialAccel;
} modeA;
//! Mode B: radius mode
/** @struct modeB
Mode B: radius mode.
*/
struct {
float angle;
float degreesPerSecond;
@ -81,7 +85,8 @@ typedef struct sParticle {
class Texture2D;
/** @brief Particle System base class.
/** @class ParticleSystem
* @brief Particle System base class.
Attributes of a Particle System:
- emission rate of the particles
- Gravity Mode (Mode A):
@ -106,11 +111,11 @@ Attributes of a Particle System:
- blending function
- texture
cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
Cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guaranteed in cocos2d,
cocos2d uses a another approach, but the results are almost identical.
cocos2d supports all the variables used by Particle Designer plus a bit more:
Cocos2d supports all the variables used by Particle Designer plus a bit more:
- spinning particles (supported when using ParticleSystemQuad)
- tangential acceleration (Gravity mode)
- radial acceleration (Gravity mode)
@ -134,101 +139,247 @@ emitter.startSpin = 0;
class CC_DLL ParticleSystem : public Node, public TextureProtocol
{
public:
/** Mode
*/
enum class Mode
{
GRAVITY,
RADIUS,
};
/** @typedef PositionType
possible types of particle positions
/** PositionType
Possible types of particle positions.
*/
enum class PositionType
{
/** Living particles are attached to the world and are unaffected by emitter repositioning. */
FREE,
FREE, /** Living particles are attached to the world and are unaffected by emitter repositioning. */
/** Living particles are attached to the world but will follow the emitter repositioning.
Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
*/
RELATIVE,
RELATIVE, /** Living particles are attached to the world but will follow the emitter repositioning.
Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.*/
/** Living particles are attached to the emitter and are translated along with it. */
GROUPED,
GROUPED, /** Living particles are attached to the emitter and are translated along with it. */
};
//* @enum
enum {
/** The Particle emitter lives forever */
/** The Particle emitter lives forever. */
DURATION_INFINITY = -1,
/** The starting size of the particle is equal to the ending size */
/** The starting size of the particle is equal to the ending size. */
START_SIZE_EQUAL_TO_END_SIZE = -1,
/** The starting radius of the particle is equal to the ending radius */
/** The starting radius of the particle is equal to the ending radius. */
START_RADIUS_EQUAL_TO_END_RADIUS = -1,
};
/** creates an initializes a ParticleSystem from a plist file.
/** Creates an initializes a ParticleSystem from a plist file.
This plist files can be created manually or with Particle Designer:
http://particledesigner.71squared.com/
@since v2.0
*/
@since v2.0
*
* @param Particle plist file name.
* @return An autoreleased ParticleSystem object.
*/
static ParticleSystem * create(const std::string& plistFile);
//! create a system with a fixed number of particles
/** Create a system with a fixed number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSystemQuad object.
*/
static ParticleSystem* createWithTotalParticles(int numberOfParticles);
//! Add a particle to the emitter
/** Add a particle to the emitter.
*
* @return True if add success.
*/
bool addParticle();
//! Initializes a particle
/** Initializes a particle.
*
* @param particle A given particle pointer.
*/
void initParticle(tParticle* particle);
//! stop emitting particles. Running particles will continue to run until they die
/** Stop emitting particles. Running particles will continue to run until they die.
*/
void stopSystem();
//! Kill all living particles.
/** Kill all living particles.
*/
void resetSystem();
//! whether or not the system is full
/** Whether or not the system is full.
*
* @return True if the system is full.
*/
bool isFull();
//! should be overridden by subclasses
/** Update the verts position data of particle,
should be overridden by subclasses.
*
* @param particle A certain particle.
* @param newPosition A new position.
*/
virtual void updateQuadWithParticle(tParticle* particle, const Vec2& newPosition);
//! should be overridden by subclasses
/** Update the VBO verts buffer which does not use batch node,
should be overridden by subclasses. */
virtual void postStep();
/** Call the update mathod with no time..
*/
virtual void updateWithNoTime(void);
/** Whether or not the particle system removed self on finish.
*
* @return True if the particle system removed self on finish.
*/
virtual bool isAutoRemoveOnFinish() const;
/** Set the particle system auto removed it self on finish.
*
* @param var True if the particle system removed self on finish.
*/
virtual void setAutoRemoveOnFinish(bool var);
// mode A
/** Gets the garvity.
*
* @return The gravity.
*/
virtual const Vec2& getGravity();
/** Sets the gravity.
*
* @param g The gravity.
*/
virtual void setGravity(const Vec2& g);
/** Gets the speed.
*
* @return The speed.
*/
virtual float getSpeed() const;
/** Sets the speed.
*
* @param speed The speed.
*/
virtual void setSpeed(float speed);
/** Gets the speed variance.
*
* @return The speed variance.
*/
virtual float getSpeedVar() const;
/** Sets the speed variance.
*
* @param speed The speed variance.
*/
virtual void setSpeedVar(float speed);
/** Gets the tangential acceleration.
*
* @return The tangential acceleration.
*/
virtual float getTangentialAccel() const;
/** Sets the tangential acceleration.
*
* @param t The tangential acceleration.
*/
virtual void setTangentialAccel(float t);
/** Gets the tangential acceleration variance.
*
* @return The tangential acceleration variance.
*/
virtual float getTangentialAccelVar() const;
/** Sets the tangential acceleration variance.
*
* @param t The tangential acceleration variance.
*/
virtual void setTangentialAccelVar(float t);
/** Gets the radial acceleration.
*
* @return The radial acceleration.
*/
virtual float getRadialAccel() const;
/** Sets the radial acceleration.
*
* @param t The radial acceleration.
*/
virtual void setRadialAccel(float t);
/** Gets the radial acceleration variance.
*
* @return The radial acceleration variance.
*/
virtual float getRadialAccelVar() const;
/** Sets the radial acceleration variance.
*
* @param t The radial acceleration variance.
*/
virtual void setRadialAccelVar(float t);
/** Whether or not the rotation of each particle to its direction.
*
* @return True if the rotation is the direction.
*/
virtual bool getRotationIsDir() const;
/** Sets the rotation of each particle to its direction.
*
* @param t True if the rotation is the direction.
*/
virtual void setRotationIsDir(bool t);
// mode B
/** Gets the start radius.
*
* @return The start radius.
*/
virtual float getStartRadius() const;
/** Sets the start radius.
*
* @param startRadius The start radius.
*/
virtual void setStartRadius(float startRadius);
/** Gets the start radius variance.
*
* @return The start radius variance.
*/
virtual float getStartRadiusVar() const;
/** Sets the start radius variance.
*
* @param startRadiusVar The start radius variance.
*/
virtual void setStartRadiusVar(float startRadiusVar);
/** Gets the end radius.
*
* @return The end radius.
*/
virtual float getEndRadius() const;
/** Sets the end radius.
*
* @param endRadius The end radius.
*/
virtual void setEndRadius(float endRadius);
/** Gets the end radius variance.
*
* @return The end radius variance.
*/
virtual float getEndRadiusVar() const;
/** Sets the end radius variance.
*
* @param endRadiusVar The end radius variance.
*/
virtual void setEndRadiusVar(float endRadiusVar);
/** Gets the number of degrees to rotate a particle around the source pos per second.
*
* @return The number of degrees to rotate a particle around the source pos per second.
*/
virtual float getRotatePerSecond() const;
/** Sets the number of degrees to rotate a particle around the source pos per second.
*
* @param degrees The number of degrees to rotate a particle around the source pos per second.
*/
virtual void setRotatePerSecond(float degrees);
/** Gets the rotate per second variance.
*
* @return The rotate per second variance.
*/
virtual float getRotatePerSecondVar() const;
/** Sets the rotate per second variance.
*
* @param degrees The rotate per second variance.
*/
virtual void setRotatePerSecondVar(float degrees);
virtual void setScale(float s) override;
@ -236,109 +387,292 @@ public:
virtual void setScaleX(float newScaleX) override;
virtual void setScaleY(float newScaleY) override;
/** Whether or not the particle system is active.
*
* @return True if the particle system is active.
*/
virtual bool isActive() const;
/** Whether or not the particle system is blend additive.
*
* @return True if the particle system is blend additive.
*/
virtual bool isBlendAdditive() const;
/** Sets the particle system blend additive.
*
* @param value True if the particle system is blend additive.
*/
virtual void setBlendAdditive(bool value);
/** Gets the batch node.
*
* @return The batch node.
*/
virtual ParticleBatchNode* getBatchNode() const;
/** Sets the batch node.
*
* @param batchNode The batch node.
*/
virtual void setBatchNode(ParticleBatchNode* batchNode);
// index of system in batch node array
/** Gets the index of system in batch node array.
*
* @return The index of system in batch node array.
*/
inline int getAtlasIndex() const { return _atlasIndex; };
/** Sets the index of system in batch node array.
*
* @param index The index of system in batch node array.
*/
inline void setAtlasIndex(int index) { _atlasIndex = index; };
/** Quantity of particles that are being simulated at the moment */
/** Gets the Quantity of particles that are being simulated at the moment.
*
* @return The Quantity of particles that are being simulated at the moment.
*/
inline unsigned int getParticleCount() const { return _particleCount; };
/** How many seconds the emitter will run. -1 means 'forever' */
/** Gets how many seconds the emitter will run. -1 means 'forever'.
*
* @return The seconds that the emitter will run. -1 means 'forever'.
*/
inline float getDuration() const { return _duration; };
/** Sets how many seconds the emitter will run. -1 means 'forever'.
*
* @param duration The seconds that the emitter will run. -1 means 'forever'.
*/
inline void setDuration(float duration) { _duration = duration; };
/** sourcePosition of the emitter */
/** Gets the source position of the emitter.
*
* @return The source position of the emitter.
*/
inline const Vec2& getSourcePosition() const { return _sourcePosition; };
/** Sets the source position of the emitter.
*
* @param The source position of the emitter.
*/
inline void setSourcePosition(const Vec2& pos) { _sourcePosition = pos; };
/** Position variance of the emitter */
/** Gets the position variance of the emitter.
*
* @return The position variance of the emitter.
*/
inline const Vec2& getPosVar() const { return _posVar; };
/** Sets the position variance of the emitter.
*
* @param pos The position variance of the emitter.
*/
inline void setPosVar(const Vec2& pos) { _posVar = pos; };
/** life, and life variation of each particle */
/** Gets the life of each particle.
*
* @return The life of each particle.
*/
inline float getLife() const { return _life; };
/** Sets the life of each particle.
*
* @param life The life of each particle.
*/
inline void setLife(float life) { _life = life; };
/** life variance of each particle */
/** Gets the life variance of each particle.
*
* @return The life variance of each particle.
*/
inline float getLifeVar() const { return _lifeVar; };
/** Sets the life variance of each particle.
*
* @param lifeVar The life variance of each particle.
*/
inline void setLifeVar(float lifeVar) { _lifeVar = lifeVar; };
/** angle and angle variation of each particle */
/** Gets the angle of each particle.
*
* @return The angle of each particle.
*/
inline float getAngle() const { return _angle; };
/** Sets the angle of each particle.
*
* @param angle The angle of each particle.
*/
inline void setAngle(float angle) { _angle = angle; };
/** angle variance of each particle */
/** Gets the angle variance of each particle.
*
* @return The angle variance of each particle.
*/
inline float getAngleVar() const { return _angleVar; };
/** Sets the angle variance of each particle.
*
* @param angleVar The angle variance of each particle.
*/
inline void setAngleVar(float angleVar) { _angleVar = angleVar; };
/** Switch between different kind of emitter modes:
- kParticleModeGravity: uses gravity, speed, radial and tangential acceleration
- kParticleModeRadius: uses radius movement + rotation
- kParticleModeGravity: uses gravity, speed, radial and tangential acceleration.
- kParticleModeRadius: uses radius movement + rotation.
*
* @return The mode of the emitter.
*/
inline Mode getEmitterMode() const { return _emitterMode; };
/** Sets the mode of the emitter.
*
* @param mode The mode of the emitter.
*/
inline void setEmitterMode(Mode mode) { _emitterMode = mode; };
/** start size in pixels of each particle */
/** Gets the start size in pixels of each particle.
*
* @return The start size in pixels of each particle.
*/
inline float getStartSize() const { return _startSize; };
/** Sets the start size in pixels of each particle.
*
* @param startSize The start size in pixels of each particle.
*/
inline void setStartSize(float startSize) { _startSize = startSize; };
/** size variance in pixels of each particle */
/** Gets the start size variance in pixels of each particle.
*
* @return The start size variance in pixels of each particle.
*/
inline float getStartSizeVar() const { return _startSizeVar; };
/** Sets the start size variance in pixels of each particle.
*
* @param sizeVar The start size variance in pixels of each particle.
*/
inline void setStartSizeVar(float sizeVar) { _startSizeVar = sizeVar; };
/** end size in pixels of each particle */
/** Gets the end size in pixels of each particle.
*
* @return The end size in pixels of each particle.
*/
inline float getEndSize() const { return _endSize; };
/** Sets the end size in pixels of each particle.
*
* @param endSize The end size in pixels of each particle.
*/
inline void setEndSize(float endSize) { _endSize = endSize; };
/** end size variance in pixels of each particle */
/** Gets the end size variance in pixels of each particle.
*
* @return The end size variance in pixels of each particle.
*/
inline float getEndSizeVar() const { return _endSizeVar; };
/** Sets the end size variance in pixels of each particle.
*
* @param sizeVar The end size variance in pixels of each particle.
*/
inline void setEndSizeVar(float sizeVar) { _endSizeVar = sizeVar; };
/** start color of each particle */
/** Gets the start color of each particle.
*
* @return The start color of each particle.
*/
inline const Color4F& getStartColor() const { return _startColor; };
/** Sets the start color of each particle.
*
* @param color The start color of each particle.
*/
inline void setStartColor(const Color4F& color) { _startColor = color; };
/** start color variance of each particle */
/** Gets the start color variance of each particle.
*
* @return The start color variance of each particle.
*/
inline const Color4F& getStartColorVar() const { return _startColorVar; };
/** Sets the start color variance of each particle.
*
* @param color The start color variance of each particle.
*/
inline void setStartColorVar(const Color4F& color) { _startColorVar = color; };
/** end color and end color variation of each particle */
/** Gets the end color and end color variation of each particle.
*
* @return The end color and end color variation of each particle.
*/
inline const Color4F& getEndColor() const { return _endColor; };
/** Sets the end color and end color variation of each particle.
*
* @param color The end color and end color variation of each particle.
*/
inline void setEndColor(const Color4F& color) { _endColor = color; };
/** end color variance of each particle */
/** Gets the end color variance of each particle.
*
* @return The end color variance of each particle.
*/
inline const Color4F& getEndColorVar() const { return _endColorVar; };
/** Sets the end color variance of each particle.
*
* @param color The end color variance of each particle.
*/
inline void setEndColorVar(const Color4F& color) { _endColorVar = color; };
//* initial angle of each particle
/** Gets the start spin of each particle.
*
* @return The start spin of each particle.
*/
inline float getStartSpin() const { return _startSpin; };
/** Sets the start spin of each particle.
*
* @param spin The start spin of each particle.
*/
inline void setStartSpin(float spin) { _startSpin = spin; };
//* initial angle of each particle
/** Gets the start spin variance of each particle.
*
* @return The start spin variance of each particle.
*/
inline float getStartSpinVar() const { return _startSpinVar; };
/** Sets the start spin variance of each particle.
*
* @param pinVar The start spin variance of each particle.
*/
inline void setStartSpinVar(float pinVar) { _startSpinVar = pinVar; };
//* initial angle of each particle
/** Gets the end spin of each particle.
*
* @return The end spin of each particle.
*/
inline float getEndSpin() const { return _endSpin; };
/** Sets the end spin of each particle.
*
* @param endSpin The end spin of each particle.
*/
inline void setEndSpin(float endSpin) { _endSpin = endSpin; };
//* initial angle of each particle
/** Gets the end spin variance of each particle.
*
* @return The end spin variance of each particle.
*/
inline float getEndSpinVar() const { return _endSpinVar; };
/** Sets the end spin variance of each particle.
*
* @param endSpinVar The end spin variance of each particle.
*/
inline void setEndSpinVar(float endSpinVar) { _endSpinVar = endSpinVar; };
/** emission rate of the particles */
/** Gets the emission rate of the particles.
*
* @return The emission rate of the particles.
*/
inline float getEmissionRate() const { return _emissionRate; };
/** Sets the emission rate of the particles.
*
* @param rate The emission rate of the particles.
*/
inline void setEmissionRate(float rate) { _emissionRate = rate; };
/** maximum particles of the system */
/** Gets the maximum particles of the system.
*
* @return The maximum particles of the system.
*/
virtual int getTotalParticles() const;
/** Sets the maximum particles of the system.
*
* @param totalParticles The maximum particles of the system.
*/
virtual void setTotalParticles(int totalParticles);
/** does the alpha value modify color */
@ -346,10 +680,17 @@ public:
inline bool isOpacityModifyRGB() const override { return _opacityModifyRGB; };
CC_DEPRECATED_ATTRIBUTE inline bool getOpacityModifyRGB() const { return isOpacityModifyRGB(); }
/** particles movement type: Free or Grouped
/** Gets the particles movement type: Free or Grouped.
@since v0.8
*
* @return The particles movement type.
*/
inline PositionType getPositionType() const { return _positionType; };
/** Sets the particles movement type: Free or Grouped.
@since v0.8
*
* @param type The particles movement type.
*/
inline void setPositionType(PositionType type) { _positionType = type; };
// Overrides

View File

@ -41,35 +41,52 @@ class EventCustom;
* @{
*/
/** @brief ParticleSystemQuad is a subclass of ParticleSystem
/** @class ParticleSystemQuad
* @brief ParticleSystemQuad is a subclass of ParticleSystem.
It includes all the features of ParticleSystem.
Special features and Limitations:
- Particle size can be any float number.
- The system can be scaled
- The particles can be rotated
- It supports subrects
- It supports batched rendering since 1.1
- The system can be scaled.
- The particles can be rotated.
- It supports subrects.
- It supports batched rendering since 1.1.
@since v0.8
*/
class CC_DLL ParticleSystemQuad : public ParticleSystem
{
public:
/** creates a Particle Emitter */
/** Creates a Particle Emitter.
*
* @return An autoreleased ParticleSystemQuad object.
*/
static ParticleSystemQuad * create();
/** creates a Particle Emitter with a number of particles */
/** Creates a Particle Emitter with a number of particles.
*
* @param numberOfParticles A given number of particles.
* @return An autoreleased ParticleSystemQuad object.
*/
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:
/** Creates an initializes a ParticleSystemQuad from a plist file.
This plist files can be created manually or with Particle Designer.
*
* @param filename Particle plist file name.
* @return An autoreleased ParticleSystemQuad object.
*/
static ParticleSystemQuad * create(const std::string& filename);
/** creates a Particle Emitter with a dictionary */
/** Creates a Particle Emitter with a dictionary.
*
* @param dictionary Particle dictionary.
* @return An autoreleased ParticleSystemQuad object.
*/
static ParticleSystemQuad * create(ValueMap &dictionary);
/** Sets a new SpriteFrame as particle.
WARNING: this method is experimental. Use setTextureWithRect instead.
*
* @param spriteFrame A given sprite frame as particle texture.
@since v0.99.4
*/
void setDisplayFrame(SpriteFrame *spriteFrame);
@ -78,12 +95,17 @@ public:
@since v0.99.4
* @js NA
* @lua NA
*
* @param texture A given texture.
8 @param rect A given rect, in points.
*/
void setTextureWithRect(Texture2D *texture, const Rect& rect);
/** listen the event that renderer was recreated on Android/WP8
/** Listen the event that renderer was recreated on Android/WP8.
* @js NA
* @lua NA
*
* @param event the event that renderer was recreated on Android/WP8.
*/
void listenRendererRecreated(EventCustom* event);

View File

@ -34,76 +34,122 @@ NS_CC_BEGIN
class Sprite;
/**
* @addtogroup misc_nodes
* @addtogroup _2d
* @{
*/
/**
@brief ProgressTimer is a subclass of Node.
It renders the inner sprite according to the percentage.
The progress can be Radial, Horizontal or vertical.
@since v0.99.1
*/
* @brief ProgressTimer is a subclass of Node.
* It renders the inner sprite according to the percentage.
* The progress can be Radial, Horizontal or vertical.
* @since v0.99.1
*/
class CC_DLL ProgressTimer : public Node
{
public:
/** Types of progress
@since v0.99.1
* @since v0.99.1
*/
enum class Type
{
/// Radial Counter-Clockwise
RADIAL,
/// Bar
BAR,
RADIAL,/** Radial Counter-Clockwise. */
BAR,/** Bar. */
};
/** Creates a progress timer with the sprite as the shape the timer goes through */
/** Creates a progress timer with the sprite as the shape the timer goes through.
*
* @param sp The sprite as the shape the timer goes through.
* @return A ProgressTimer.
*/
static ProgressTimer* create(Sprite* sp);
/** Change the percentage to change progress. */
/** Change the percentage to change progress.
*
* @return A Type
*/
inline Type getType() const { return _type; }
/** Percentages are from 0 to 100 */
/** Percentages are from 0 to 100.
*
* @return Percentages.
*/
inline float getPercentage() const {return _percentage; }
/** The image to show the progress percentage, retain */
/** The image to show the progress percentage, retain.
*
* @return A sprite.
*/
inline Sprite* getSprite() const { return _sprite; }
/** Set the initial percentage values.
*
* @param percentage The initial percentage values.
*/
void setPercentage(float percentage);
/** Set the sprite as the shape.
*
* @param sprite The sprite as the shape.
*/
void setSprite(Sprite *sprite);
/** Set the ProgressTimer type.
*
* @param type Is an Type.
*/
void setType(Type type);
/**
/** Set the Reverse direction.
* @js setReverseDirection
* @lua setReverseDirection
* @param reverse If reverse is false it will clockwise,if is true it will Anti-clockwise.
*/
void setReverseProgress(bool reverse);
/** Return the Reverse direction.
*
* @return If the direction is Anti-clockwise,it will return true.
*/
inline bool isReverseDirection() { return _reverseDirection; };
/** Set the Reverse direction.
*
* @param value If value is false it will clockwise,if is true it will Anti-clockwise.
*/
inline void setReverseDirection(bool value) { _reverseDirection = value; };
/**
* Midpoint is used to modify the progress start position.
* If you're using radials type then the midpoint changes the center point
* If you're using bar type the the midpoint changes the bar growth
* If you're using radials type then the midpoint changes the center point.
* If you're using bar type the the midpoint changes the bar growth.
* it expands from the center but clamps to the sprites edge so:
* you want a left to right then set the midpoint all the way to Vec2(0,y)
* you want a right to left then set the midpoint all the way to Vec2(1,y)
* you want a bottom to top then set the midpoint all the way to Vec2(x,0)
* you want a top to bottom then set the midpoint all the way to Vec2(x,1)
* you want a left to right then set the midpoint all the way to Vec2(0,y).
* you want a right to left then set the midpoint all the way to Vec2(1,y).
* you want a bottom to top then set the midpoint all the way to Vec2(x,0).
* you want a top to bottom then set the midpoint all the way to Vec2(x,1).
* @param point A Vec2 point.
*/
void setMidpoint(const Vec2& point);
/** Returns the Midpoint */
/** Returns the Midpoint.
*
* @return A Vec2.
*/
Vec2 getMidpoint() const;
/**
* This allows the bar type to move the component at a specific rate
* This allows the bar type to move the component at a specific rate.
* Set the component to 0 to make sure it stays at 100%.
* For example you want a left to right bar but not have the height stay 100%
* Set the rate to be Vec2(0,1); and set the midpoint to = Vec2(0,.5f);
* For example you want a left to right bar but not have the height stay 100%.
* Set the rate to be Vec2(0,1); and set the midpoint to = Vec2(0,.5f).
* @param barChangeRate A Vec2.
*/
inline void setBarChangeRate(const Vec2& barChangeRate ) { _barChangeRate = barChangeRate; }
/** Returns the BarChangeRate */
/** Returns the BarChangeRate.
*
* @return A barChangeRate.
*/
inline Vec2 getBarChangeRate() const { return _barChangeRate; }
// Overrides

View File

@ -37,115 +37,227 @@ NS_CC_BEGIN
class EventCustom;
/**
* @addtogroup textures
* @addtogroup _2d
* @{
*/
/**
@brief RenderTexture is a generic rendering target. To render things into it,
simply construct a render target, call begin on it, call visit on any cocos
scenes or objects to render them, and call end. For convenience, render texture
adds a sprite as it's display child with the results, so you can simply add
the render texture to your scene and treat it like any other CocosNode.
There are also functions for saving the render texture to disk in PNG or JPG format.
@since v0.8.1
*/
* @brief RenderTexture is a generic rendering target. To render things into it,
* simply construct a render target, call begin on it, call visit on any cocos
* scenes or objects to render them, and call end. For convenience, render texture
* adds a sprite as it's display child with the results, so you can simply add
* the render texture to your scene and treat it like any other CocosNode.
* There are also functions for saving the render texture to disk in PNG or JPG format.
* @since v0.8.1
*/
class CC_DLL RenderTexture : public Node
{
public:
/** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/
/** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format.
*
* @param w The RenderTexture object width.
* @param h The RenderTexture object height.
* @param format In Points and a pixel format( only RGB and RGBA formats are valid ).
* @param depthStencilFormat The depthStencil format.
*/
static RenderTexture * create(int w ,int h, Texture2D::PixelFormat format, GLuint depthStencilFormat);
/** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
/** Creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid.
*
* @param w The RenderTexture object width.
* @param h The RenderTexture object height.
* @param format In Points and a pixel format( only RGB and RGBA formats are valid ).
*/
static RenderTexture * create(int w, int h, Texture2D::PixelFormat format);
/** creates a RenderTexture object with width and height in Points, pixel format is RGBA8888 */
/** Creates a RenderTexture object with width and height in Points, pixel format is RGBA8888.
*
* @param w The RenderTexture object width.
* @param h The RenderTexture object height.
*/
static RenderTexture * create(int w, int h);
/** starts grabbing */
/** Starts grabbing. */
virtual void begin();
/** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */
/** Starts rendering to the texture while clearing the texture first.
* This is more efficient then calling -clear first and then -begin.
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
virtual void beginWithClear(float r, float g, float b, float a);
/** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */
/** Starts rendering to the texture while clearing the texture first.
* This is more efficient then calling -clear first and then -begin.
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
virtual void beginWithClear(float r, float g, float b, float a, float depthValue);
/** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */
/** Starts rendering to the texture while clearing the texture first.
* This is more efficient then calling -clear first and then -begin.
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
* @param depthValue A specified depth value.
* @param stencilValue A specified stencil value.
*/
virtual void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue);
/** end is key word of lua, use other name to export to lua. */
/** End is key word of lua, use other name to export to lua. */
inline void endToLua(){ end();};
/** ends grabbing*/
/** Ends grabbing. */
virtual void end();
/** clears the texture with a color */
/** Clears the texture with a color.
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
void clear(float r, float g, float b, float a);
/** clears the texture with a specified depth value */
/** Clears the texture with a specified depth value.
*
* @param A specified depth value.
*/
virtual void clearDepth(float depthValue);
/** clears the texture with a specified stencil value */
virtual void clearStencil(int stencilValue);
/* creates a new Image from with the texture's data.
Caller is responsible for releasing it by calling delete.
/** Clears the texture with a specified stencil value.
*
* @param A specified stencil value.
*/
virtual void clearStencil(int stencilValue);
/* Creates a new Image from with the texture's data.
* Caller is responsible for releasing it by calling delete.
*
* @param flipImage Whether or not to flip image.
* @return An image.
*/
Image* newImage(bool flipImage = true);
CC_DEPRECATED_ATTRIBUTE Image* newCCImage(bool flipImage = true) { return newImage(flipImage); };
/** 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.
/** 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.
*
* @param filename The file name.
* @param isRGBA The file is RGBA or not.
* @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful.
*/
bool saveToFile(const std::string& filename, bool isRGBA = true, std::function<void (RenderTexture*, const std::string&)> callback = nullptr);
/** 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.
* Notes: since v3.x, saveToFile will generate a custum command, which will be called in the following render->render().
* So if this function is called in a event handler, the actual save file will be called in the next frame. If we switch to a different scene, the game will crash.
* To solve this, add Director::getInstance()->getRenderer()->render(); after this function.
*
* @param filename The file name.
* @param format The image format.
* @param isRGBA The file is RGBA or not.
* @param callback When the file is save finished,it will callback this function.
* @return Returns true if the operation is successful.
*/
bool saveToFile(const std::string& filename, Image::Format format, bool isRGBA = true, std::function<void (RenderTexture*, const std::string&)> callback = nullptr);
/** Listen "come to background" message, and save render texture.
It only has effect on Android.
* It only has effect on Android.
*
* @param event Event Custom.
*/
void listenToBackground(EventCustom *event);
/** Listen "come to foreground" message and restore the frame buffer object
It only has effect on Android.
/** Listen "come to foreground" message and restore the frame buffer object.
* It only has effect on Android.
*
* @param event Event Custom.
*/
void listenToForeground(EventCustom *event);
/** Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw" is true. */
/** Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw" is true.
*
* @return Clear flags.
*/
inline unsigned int getClearFlags() const { return _clearFlags; };
/** Set flags.
*
* @param clearFlags Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
*/
inline void setClearFlags(unsigned int clearFlags) { _clearFlags = clearFlags; };
/** Clear color value. Valid only when "autoDraw" is true. */
/** Clear color value. Valid only when "autoDraw" is true.
*
* @return Color value.
*/
inline const Color4F& getClearColor() const { return _clearColor; };
/** Set color value.
*
* @param clearColor Color value.
*/
inline void setClearColor(const Color4F &clearColor) { _clearColor = clearColor; };
/** Value for clearDepth. Valid only when "autoDraw" is true. */
/** Value for clearDepth. Valid only when "autoDraw" is true.
*
* @return Value for clearDepth.
*/
inline float getClearDepth() const { return _clearDepth; };
/** Set Value for clearDepth.
*
* @param clearDepth Value for clearDepth.
*/
inline void setClearDepth(float clearDepth) { _clearDepth = clearDepth; };
/** Value for clear Stencil. Valid only when "autoDraw" is true */
/** Value for clear Stencil. Valid only when "autoDraw" is true.
*
* @return Value for clear Stencil.
*/
inline int getClearStencil() const { return _clearStencil; };
/** Set Value for clear Stencil.
*
* @param clearStencil Value for clear Stencil.
*/
inline void setClearStencil(int clearStencil) { _clearStencil = clearStencil; };
/** When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons.
Will be enabled in the future.
* Will be enabled in the future.
*
* @return Return the autoDraw value.
*/
inline bool isAutoDraw() const { return _autoDraw; };
/** Set a valve to control whether or not render its children into the texture automatically.
*
* @param isAutoDraw Whether or not render its children into the texture automatically.
*/
inline void setAutoDraw(bool isAutoDraw) { _autoDraw = isAutoDraw; };
/** Gets the Sprite being used. */
/** Gets the Sprite being used.
*
* @return A Sprite.
*/
inline Sprite* getSprite() const { return _sprite; };
/** Sets the Sprite being used. */
/** Sets the Sprite being used.
*
* @param A Sprite.
*/
inline void setSprite(Sprite* sprite) {
CC_SAFE_RETAIN(sprite);
CC_SAFE_RELEASE(_sprite);
@ -156,24 +268,41 @@ public:
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;
//flag: use stack matrix computed from scene hierarchy or generate new modelView and projection matrix
/** Flag: Use stack matrix computed from scene hierarchy or generate new modelView and projection matrix.
*
* @param keepMatrix Wether or not use stack matrix computed from scene hierarchy or generate new modelView and projection matrix.
*/
void setKeepMatrix(bool keepMatrix);
/**Used for grab part of screen to a texture.
//rtBegin: the position of renderTexture on the fullRect
//fullRect: the total size of screen
//fullViewport: the total viewportSize
*/
* @param rtBegin The position of renderTexture on the fullRect.
* @param fullRect The total size of screen.
* @param fullViewport The total viewportSize.
*/
void setVirtualViewport(const Vec2& rtBegin, const Rect& fullRect, const Rect& fullViewport);
public:
// FIXME: should be procted.
// but due to a bug in PowerVR + Android,
// the constructor is public again
/** FIXME: should be procted.
* but due to a bug in PowerVR + Android,
* the constructor is public again.
*/
RenderTexture();
virtual ~RenderTexture();
/** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
/** Initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid.
*
* @param w The RenderTexture object width.
* @param h The RenderTexture object height.
* @param format In Points and a pixel format( only RGB and RGBA formats are valid ).
* @return If successed,it will return true.
*/
bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format);
/** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/
/** Initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format.
*
* @param w The RenderTexture object width.
* @param h The RenderTexture object height.
* @param format In Points and a pixel format( only RGB and RGBA formats are valid ).
* @param depthStencilFormat The depthStencil format.
* @return If successed,it will return true.
*/
bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format, GLuint depthStencilFormat);
protected:

View File

@ -72,6 +72,7 @@ public:
*
* @param size The predefined size of scene.
* @return An autoreleased Scene object.
* @js NA
*/
static Scene *createWithSize(const Size& size);
@ -81,24 +82,25 @@ public:
/** Get all cameras.
*
* @return The vector of all cameras.
* @js NA
*/
const std::vector<Camera*>& getCameras() const { return _cameras; }
/** Get the default camera.
*
* @js NA
* @return The default camera of scene.
*/
Camera* getDefaultCamera() const { return _defaultCamera; }
/** Get lights.
*
* @return The vector of lights.
* @js NA
*/
const std::vector<BaseLight*>& getLights() const { return _lights; }
/** Render the scene.
*
* @param renderer The renderer use to render the scene.
* @js NA
*/
void render(Renderer* renderer);
@ -139,14 +141,14 @@ public:
virtual void addChild(Node* child, int zOrder, int tag) override;
virtual void addChild(Node* child, int zOrder, const std::string &name) override;
/** Get the physics world of the scene.
*
* @return The physics world of the scene.
* @js NA
*/
inline PhysicsWorld* getPhysicsWorld() { return _physicsWorld; }
/** Create a scene with physics.
*
* @return An autoreleased Scene object with physics.
* @js NA
*/
static Scene *createWithPhysics();

View File

@ -39,7 +39,7 @@ THE SOFTWARE.
NS_CC_BEGIN
/**
* @addtogroup sprite_nodes
* @addtogroup _2d
* @{
*/
@ -47,41 +47,55 @@ NS_CC_BEGIN
class Sprite;
/** SpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
* (often known as "batch draw").
*
* A SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
* Only the Sprites that are contained in that texture can be added to the SpriteBatchNode.
* All Sprites added to a SpriteBatchNode are drawn in one OpenGL ES draw call.
* If the Sprites are not added to a SpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
*
*
* Limitations:
* - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is Sprite or any subclass of Sprite. eg: particles, labels and layer can't be added to a SpriteBatchNode.
* - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture.
*
* @since v0.7.1
*/
* (often known as "batch draw").
*
* A SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
* Only the Sprites that are contained in that texture can be added to the SpriteBatchNode.
* All Sprites added to a SpriteBatchNode are drawn in one OpenGL ES draw call.
* If the Sprites are not added to a SpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.
*
*
* Limitations:
* - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is Sprite or any subclass of Sprite. eg: particles, labels and layer can't be added to a SpriteBatchNode.
* - Either all its children are Aliased or Antialiased. It can't be a mix. This is because "alias" is a property of the texture, and all the sprites share the same texture.
*
* @since v0.7.1
*/
class CC_DLL SpriteBatchNode : public Node, public TextureProtocol
{
static const int DEFAULT_CAPACITY = 29;
public:
/** creates a SpriteBatchNode with a texture2d and capacity of children.
The capacity will be increased in 33% in runtime if it runs out of space.
/** Creates a SpriteBatchNode with a texture2d and capacity of children.
* The capacity will be increased in 33% in runtime if it runs out of space.
*
* @param tex A texture2d.
* @param capacity The capacity of children.
* @return Return an autorelease object.
*/
static SpriteBatchNode* createWithTexture(Texture2D* tex, ssize_t capacity = DEFAULT_CAPACITY);
/** creates a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children.
The capacity will be increased in 33% in runtime if it runs out of space.
The file will be loaded using the TextureMgr.
/** Creates a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children.
* The capacity will be increased in 33% in runtime if it runs out of space.
* The file will be loaded using the TextureMgr.
*
* @param fileImage A file image (.png, .jpeg, .pvr, etc).
* @param capacity The capacity of children.
* @return Return an autorelease object.
*/
static SpriteBatchNode* create(const std::string& fileImage, ssize_t capacity = DEFAULT_CAPACITY);
/** returns the TextureAtlas object */
/** Returns the TextureAtlas object.
*
* @return The TextureAtlas object.
*/
inline TextureAtlas* getTextureAtlas() { return _textureAtlas; }
/** sets the TextureAtlas object */
/** Sets the TextureAtlas object.
*
* @param textureAtlas The TextureAtlas object.
*/
inline void setTextureAtlas(TextureAtlas* textureAtlas)
{
if (textureAtlas != _textureAtlas)
@ -92,25 +106,66 @@ public:
}
}
/** returns an array with the descendants (children, gran children, etc.).
This is specific to BatchNode. In order to use the children, use getChildren() instead */
/** Returns an array with the descendants (children, gran children, etc.).
* This is specific to BatchNode. In order to use the children, use getChildren() instead.
*
* @return An array with the descendants (children, gran children, etc.).
*/
inline const std::vector<Sprite*>& getDescendants() const { return _descendants; }
/** Increase the Atlas Capacity. */
void increaseAtlasCapacity();
/** removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
@warning Removing a child from a SpriteBatchNode is very slow
*/
/** Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
*
* @param index A certain index.
* @param doCleanup Whether or not to cleanup the running actions.
* @warning Removing a child from a SpriteBatchNode is very slow.
*/
void removeChildAtIndex(ssize_t index, bool doCleanup);
/** Append the child.
*
* @param sprite A Sprite.
*/
void appendChild(Sprite* sprite);
/** Remove a sprite from Atlas.
*
* @param sprite A Sprite.
*/
void removeSpriteFromAtlas(Sprite *sprite);
/** Rebuild index with a sprite all child.
*
* @param parent The parent sprite.
* @param index The child index.
* @return Index.
*/
ssize_t rebuildIndexInOrder(Sprite *parent, ssize_t index);
/** Get the Max image block index,in all child.
*
* @param sprite The parent sprite.
* @return Index.
*/
ssize_t highestAtlasIndexInChild(Sprite *sprite);
/** Get the Min image block index,in all child.
*
* @param sprite The parent sprite.
* @return Index.
*/
ssize_t lowestAtlasIndexInChild(Sprite *sprite);
/** Get the nearest index from the sprite in z.
*
* @param sprite The parent sprite.
* @param z Z order for drawing priority.
* @return Index.
*/
ssize_t atlasIndexForChild(Sprite *sprite, int z);
/* Sprites use this to start sortChildren, don't call this manually */
/* Sprites use this to start sortChildren, don't call this manually. */
void reorderBatch(bool reorder);
//
@ -121,9 +176,9 @@ public:
virtual void setTexture(Texture2D *texture) override;
/**
*@code
*When this function bound into js or lua,the parameter will be changed
*In js: var setBlendFunc(var src, var dst)
*@endcode
* When this function bound into js or lua,the parameter will be changed.
* In js: var setBlendFunc(var src, var dst).
* @endcode
* @lua NA
*/
virtual void setBlendFunc(const BlendFunc &blendFunc) override;
@ -147,13 +202,13 @@ public:
virtual std::string getDescription() const override;
/** Inserts a quad at a certain index into the texture atlas. The Sprite won't be added into the children array.
This method should be called only when you are dealing with very big AtlasSrite and when most of the Sprite won't be updated.
For example: a tile map (TMXMap) or a label with lots of characters (LabelBMFont)
* This method should be called only when you are dealing with very big AtlasSrite and when most of the Sprite won't be updated.
* For example: a tile map (TMXMap) or a label with lots of characters (LabelBMFont).
*/
void insertQuadFromSprite(Sprite *sprite, ssize_t index);
/* This is the opposite of "addQuadFromSprite.
It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
*/
* It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
*/
SpriteBatchNode * addSpriteWithoutQuad(Sprite *child, int z, int aTag);
CC_CONSTRUCTOR_ACCESS:
@ -202,7 +257,7 @@ protected:
};
// end of sprite_nodes group
/// @}
/** @} */
NS_CC_END

View File

@ -55,6 +55,7 @@ class Texture2D;
* @brief Singleton that handles the loading of the sprite frames.
It saves in a cache the sprite frames.
@since v0.9
@js cc.spriteFrameCache
*/
class CC_DLL SpriteFrameCache : public Ref
{
@ -62,17 +63,23 @@ public:
/** Returns the shared instance of the Sprite Frame cache.
*
* @return The instance of the Sprite Frame Cache.
* @js NA
*/
static SpriteFrameCache* getInstance();
/** @deprecated Use getInstance() instead */
/** @deprecated Use getInstance() instead
@js NA
*/
CC_DEPRECATED_ATTRIBUTE static SpriteFrameCache* sharedSpriteFrameCache() { return SpriteFrameCache::getInstance(); }
/** Destroys the cache. It releases all the Sprite Frames and the retained instance.
* @js NA
*/
static void destroyInstance();
/** @deprecated Use destroyInstance() instead */
/** @deprecated Use destroyInstance() instead
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE static void purgeSharedSpriteFrameCache() { return SpriteFrameCache::destroyInstance(); }
/** Destructor.
@ -117,7 +124,7 @@ public:
void addSpriteFramesWithFile(const std::string&plist, Texture2D *texture);
/** Adds multiple Sprite Frames from a plist file content. The texture will be associated with the created sprite frames.
* @js addSpriteFrames
* @js NA
* @lua addSpriteFrames
*
* @param plist_content Plist file content string.
@ -144,6 +151,7 @@ public:
/** Removes unused sprite frames.
* Sprite Frames that have a retain count of 1 will be deleted.
* It is convenient to call this method after when starting a new Scene.
* @js NA
*/
void removeUnusedSpriteFrames();
@ -167,6 +175,7 @@ public:
* It is convenient to call this method when a specific texture needs to be removed.
*
* @param plist_content The string of the plist content that needs to removed.
* @js NA
*/
void removeSpriteFramesFromFileContent(const std::string& plist_content);

View File

@ -38,43 +38,40 @@ class TMXTilesetInfo;
struct _ccCArray;
/**
* @addtogroup tilemap_parallax_nodes
* @addtogroup _2d
* @{
*/
/** @brief TMXLayer represents the TMX layer.
It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
The benefits of using Sprite objects as tiles are:
- tiles (Sprite) can be rotated/scaled/moved with a nice API
If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
glAlphaFunc( GL_GREATER, value )
"value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
value, like 0.5.
For further information, please see the programming guide:
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
@since v0.8.1
Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in TMXXMLParser.h.
@since 1.1
*/
* It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
* If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
* The benefits of using Sprite objects as tiles are:
* - tiles (Sprite) can be rotated/scaled/moved with a nice API.
* If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
* then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
* On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
* Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
* glAlphaFunc( GL_GREATER, value ).
* "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
* The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
* value, like 0.5.
* For further information, please see the programming guide:
* http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
* @since v0.8.1
* Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in TMXXMLParser.h.
* @since 1.1
*/
class CC_DLL TMXLayer : public SpriteBatchNode
{
public:
/** creates a TMXLayer with an tileset info, a layer info and a map info */
/** Creates a TMXLayer with an tileset info, a layer info and a map info.
*
* @param tilesetInfo An tileset info.
* @param layerInfo A layer info.
* @param mapInfo A map info.
* @return An autorelease object.
*/
static TMXLayer * create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/**
* @js ctor
@ -86,95 +83,185 @@ public:
*/
virtual ~TMXLayer();
/** initializes a TMXLayer with a tileset info, a layer info and a map info */
/** Initializes a TMXLayer with a tileset info, a layer info and a map info.
*
* @param tilesetInfo An tileset info.
* @param layerInfo A layer info.
* @param mapInfo A map info.
* @return If initializes successit will return true.
*/
bool initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/** dealloc the map that contains the tile position from memory.
Unless you want to know at runtime the tiles positions, you can safely call this method.
If you are going to call layer->tileGIDAt() then, don't release the map
*/
/** Dealloc the map that contains the tile position from memory.
* Unless you want to know at runtime the tiles positions, you can safely call this method.
* If you are going to call layer->tileGIDAt() then, don't release the map.
*/
void releaseMap();
/** returns the tile (Sprite) at a given a tile coordinate.
The returned Sprite will be already added to the TMXLayer. Don't add it again.
The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- layer->removeChild(sprite, cleanup);
- or layer->removeTileAt(Vec2(x,y));
*/
/** Returns the tile (Sprite) at a given a tile coordinate.
* The returned Sprite will be already added to the TMXLayer. Don't add it again.
* The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
* You can remove either by calling:
* - layer->removeChild(sprite, cleanup);
* - or layer->removeTileAt(Vec2(x,y));
*
* @param tileCoordinate A tile coordinate.
* @return Returns the tile (Sprite) at a given a tile coordinate.
*/
Sprite* getTileAt(const Vec2& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Sprite* tileAt(const Vec2& tileCoordinate) { return getTileAt(tileCoordinate); };
/** returns the tile gid at a given tile coordinate. It also returns the tile flags.
This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap])
/** Returns the tile gid at a given tile coordinate. It also returns the tile flags.
* This method requires the the tile map has not been previously released (eg. don't call [layer releaseMap]).
*
* @param tileCoordinate The tile coordinate.
* @param flags Tile flags.
* @return Returns the tile gid at a given tile coordinate. It also returns the tile flags.
*/
uint32_t getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags = nullptr);
CC_DEPRECATED_ATTRIBUTE uint32_t tileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags = nullptr){
return getTileGIDAt(tileCoordinate, flags);
};
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
*/
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
*
* @param gid The tile gid.
* @param tileCoordinate The tile coordinate.
*/
void setTileGID(uint32_t gid, const Vec2& tileCoordinate);
/** sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
Use withFlags if the tile flags need to be changed as well
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
* Use withFlags if the tile flags need to be changed as well.
*
* @param gid The tile gid.
* @param tileCoordinate The tile coordinate.
* @param flags The tile flags.
*/
void setTileGID(uint32_t gid, const Vec2& tileCoordinate, TMXTileFlags flags);
/** removes a tile at given tile coordinate */
/** Removes a tile at given tile coordinate.
*
* @param tileCoordinate The tile coordinate.
*/
void removeTileAt(const Vec2& tileCoordinate);
/** returns the position in points of a given tile coordinate */
/** Returns the position in points of a given tile coordinate.
*
* @param tileCoordinate The tile coordinate.
* @return The position in points of a given tile coordinate.
*/
Vec2 getPositionAt(const Vec2& tileCoordinate);
CC_DEPRECATED_ATTRIBUTE Vec2 positionAt(const Vec2& tileCoordinate) { return getPositionAt(tileCoordinate); };
/** return the value for the specific property name */
/** Return the value for the specific property name.
*
* @param propertyName The specific property name.
* @return Return the value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const std::string& propertyName) const { return getProperty(propertyName); };
/** Creates the tiles */
/** Creates the tiles. */
void setupTiles();
/** Get the layer name.
*
* @return The layer name.
*/
inline const std::string& getLayerName(){ return _layerName; }
/** Set the layer name.
*
* @param layerName The layer name.
*/
inline void setLayerName(const std::string& layerName){ _layerName = layerName; }
/** size of the layer in tiles */
/** Size of the layer in tiles.
*
* @return Size of the layer in tiles.
*/
inline const Size& getLayerSize() const { return _layerSize; };
/** Set size of the layer in tiles.
*
* @param size Size of the layer in tiles.
*/
inline void setLayerSize(const Size& size) { _layerSize = size; };
/** size of the map's tile (could be different from the tile's size) */
/** Size of the map's tile (could be different from the tile's size).
*
* @return The size of the map's tile.
*/
inline const Size& getMapTileSize() const { return _mapTileSize; };
/** Set the size of the map's tile.
*
* @param size The size of the map's tile.
*/
inline void setMapTileSize(const Size& size) { _mapTileSize = size; };
/** pointer to the map of tiles
/** Pointer to the map of tiles.
* @js NA
* @lua NA
* @return Pointer to the map of tiles.
*/
uint32_t* getTiles() const { return _tiles; };
/** Set a pointer to the map of tiles.
*
* @param tiles A pointer to the map of tiles.
*/
void setTiles(uint32_t* tiles) { _tiles = tiles; };
/** Tileset information for the layer */
/** Tileset information for the layer.
*
* @return Tileset information for the layer.
*/
inline TMXTilesetInfo* getTileSet() const { return _tileSet; };
/** Set tileset information for the layer.
*
* @param The tileset information for the layer.
*/
inline void setTileSet(TMXTilesetInfo* info) {
CC_SAFE_RETAIN(info);
CC_SAFE_RELEASE(_tileSet);
_tileSet = info;
};
/** Layer orientation, which is the same as the map orientation */
/** Layer orientation, which is the same as the map orientation.
*
* @return Layer orientation, which is the same as the map orientation.
*/
inline int getLayerOrientation() const { return _layerOrientation; };
/** Set layer orientation, which is the same as the map orientation.
*
* @param orientation Layer orientation,which is the same as the map orientation.
*/
inline void setLayerOrientation(int orientation) { _layerOrientation = orientation; };
/** properties from the layer. They can be added using Tiled */
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline const ValueMap& getProperties() const { return _properties; };
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline ValueMap& getProperties() { return _properties; };
/** Set an Properties from to layer.
*
* @param properties It is used to set the layer Properties.
*/
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
@ -244,7 +331,7 @@ protected:
};
// end of tilemap_parallax_nodes group
/// @}
/** @} */
NS_CC_END

View File

@ -35,13 +35,13 @@ THE SOFTWARE.
NS_CC_BEGIN
/**
* @addtogroup tilemap_parallax_nodes
* @addtogroup _2d
* @{
*/
/** @brief TMXObjectGroup represents the TMX object group.
@since v0.99.0
*/
* @since v0.99.0
*/
class CC_DLL TMXObjectGroup : public Ref
{
public:
@ -54,42 +54,75 @@ public:
* @lua NA
*/
virtual ~TMXObjectGroup();
/** Get the group name.
*
* @return The group name.
*/
inline const std::string& getGroupName() const { return _groupName; }
/** Set the group name.
*
* @param groupname A string,it is used to set the group name.
*/
inline void setGroupName(const std::string& groupName){ _groupName = groupName; }
/** return the value for the specific property name */
/** Return the value for the specific property name.
*
* @param propertyName The specific property name.
* @return Return the value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const std::string& propertyName) const { return getProperty(propertyName); };
/** return the dictionary for the specific object name.
It will return the 1st object found on the array for the given name.
*/
/** Return the dictionary for the specific object name.
* It will return the 1st object found on the array for the given name.
*
* @return Return the dictionary for the specific object name.
*/
ValueMap getObject(const std::string& objectName) const;
CC_DEPRECATED_ATTRIBUTE ValueMap objectNamed(const std::string& objectName) const { return getObject(objectName); };
/** Gets the offset position of child objects */
/** Gets the offset position of child objects.
*
* @return The offset position of child objects.
*/
inline const Vec2& getPositionOffset() const { return _positionOffset; };
/** Sets the offset position of child objects */
/** Sets the offset position of child objects.
*
* @param offset The offset position of child objects.
*/
inline void setPositionOffset(const Vec2& offset) { _positionOffset = offset; };
/** Gets the list of properties stored in a dictionary */
/** Gets the list of properties stored in a dictionary.
*
* @return The list of properties stored in a dictionary.
*/
inline const ValueMap& getProperties() const { return _properties; };
inline ValueMap& getProperties() { return _properties; };
/** Sets the list of properties */
/** Sets the list of properties.
*
* @param properties The list of properties.
*/
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
/** Gets the array of the objects */
/** Gets the array of the objects.
*
* @return The array of the objects.
*/
inline const ValueVector& getObjects() const { return _objects; };
inline ValueVector& getObjects() { return _objects; };
/** Sets the array of the objects */
/** Sets the array of the objects.
*
* @param objects The array of the objects.
*/
inline void setObjects(const ValueVector& objects) {
_objects = objects;
};
@ -106,7 +139,7 @@ protected:
};
// end of tilemap_parallax_nodes group
/// @}
/** @} */
NS_CC_END

View File

@ -45,26 +45,33 @@ class ActionInterval;
class Node;
class NodeGrid;
/** @brief TransitionEaseScene can ease the actions of the scene protocol.
/** @class TransitionEaseScene
* @brief TransitionEaseScene can ease the actions of the scene protocol.
@since v0.8.2
*/
class CC_DLL TransitionEaseScene// : public Ref
{
public:
/** Constructor.
*/
virtual ~TransitionEaseScene() {}
/** returns the Ease action that will be performed on a linear action.
/** Returns the Ease action that will be performed on a linear action.
@since v0.8.2
*/
*
* @param action A given interval action.
* @return The Ease action that will be performed on a linear action.
*/
virtual ActionInterval * easeActionWithAction(ActionInterval * action) = 0;
};
/** @brief Base class for Transition scenes
/** @class TransitionScene
* @brief Base class for Transition scenes.
*/
class CC_DLL TransitionScene : public Scene
{
public:
/** Orientation Type used by some transitions
/** Orientation Type used by some transitions.
*/
enum class Orientation
{
@ -78,13 +85,20 @@ public:
DOWN_OVER = 1,
};
/** creates a base transition with duration and incoming scene */
/** Creates a base transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionScene object.
*/
static TransitionScene * create(float t, Scene *scene);
/** called after the transition finishes */
/** Called after the transition finishes.
*/
void finish(void);
/** used by some transitions to hide the outer scene */
/** Used by some transitions to hide the outer scene.
*/
void hideOutShowIn(void);
//
@ -116,13 +130,20 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionScene);
};
/** @brief A Transition that supports orientation like.
* Possible orientation: LeftOver, RightOver, UpOver, DownOver
*/
/** @class TransitionSceneOriented
* @brief A Transition that supports orientation like.
* Possible orientation: LeftOver, RightOver, UpOver, DownOver
*/
class CC_DLL TransitionSceneOriented : public TransitionScene
{
public:
/** creates a base transition with duration and incoming scene */
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @param orientation A given orientation: LeftOver, RightOver, UpOver, DownOver.
* @return A autoreleased TransitionSceneOriented object.
*/
static TransitionSceneOriented * create(float t,Scene* scene, Orientation orientation);
CC_CONSTRUCTOR_ACCESS:
@ -139,12 +160,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSceneOriented);
};
/** @brief TransitionRotoZoom:
/** @class TransitionRotoZoom
* @brief TransitionRotoZoom:
Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
*/
class CC_DLL TransitionRotoZoom : public TransitionScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionRotoZoom object.
*/
static TransitionRotoZoom* create(float t, Scene* scene);
//
@ -161,12 +189,19 @@ private:
};
/** @brief TransitionJumpZoom:
/** @class TransitionJumpZoom
* @brief TransitionJumpZoom:
Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
*/
class CC_DLL TransitionJumpZoom : public TransitionScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionJumpZoom object.
*/
static TransitionJumpZoom* create(float t, Scene* scene);
//
@ -182,15 +217,25 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionJumpZoom);
};
/** @brief TransitionMoveInL:
/** @class TransitionMoveInL
* @brief TransitionMoveInL:
Move in from to the left the incoming scene.
*/
class CC_DLL TransitionMoveInL : public TransitionScene, public TransitionEaseScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionMoveInL object.
*/
static TransitionMoveInL* create(float t, Scene* scene);
/** returns the action that will be performed */
/** Returns the action that will be performed.
*
* @return The action that will be performed.
*/
virtual ActionInterval* action(void);
virtual ActionInterval* easeActionWithAction(ActionInterval * action) override;
@ -212,12 +257,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInL);
};
/** @brief TransitionMoveInR:
/** @class TransitionMoveInR
* @brief TransitionMoveInR:
Move in from to the right the incoming scene.
*/
class CC_DLL TransitionMoveInR : public TransitionMoveInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionMoveInR object.
*/
static TransitionMoveInR* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -231,12 +283,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInR);
};
/** @brief TransitionMoveInT:
/** @class TransitionMoveInT
* @brief TransitionMoveInT:
Move in from to the top the incoming scene.
*/
class CC_DLL TransitionMoveInT : public TransitionMoveInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionMoveInT object.
*/
static TransitionMoveInT* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -250,12 +309,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInT);
};
/** @brief TransitionMoveInB:
/** @class TransitionMoveInB
* @brief TransitionMoveInB:
Move in from to the bottom the incoming scene.
*/
class CC_DLL TransitionMoveInB : public TransitionMoveInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionMoveInB object.
*/
static TransitionMoveInB* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -269,17 +335,27 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionMoveInB);
};
/** @brief TransitionSlideInL:
/** @class TransitionSlideInL
* @brief TransitionSlideInL:
Slide in the incoming scene from the left border.
*/
class CC_DLL TransitionSlideInL : public TransitionScene, public TransitionEaseScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSlideInL object.
*/
static TransitionSlideInL* create(float t, Scene* scene);
virtual ActionInterval* easeActionWithAction(ActionInterval * action) override;
/** returns the action that will be performed by the incoming and outgoing scene */
/** Returns the action that will be performed by the incoming and outgoing scene.
*
* @return The action that will be performed by the incoming and outgoing scene.
*/
virtual ActionInterval* action(void);
//
@ -301,15 +377,22 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInL);
};
/** @brief TransitionSlideInR:
/** @class TransitionSlideInR
*@brief TransitionSlideInR:
Slide in the incoming scene from the right border.
*/
class CC_DLL TransitionSlideInR : public TransitionSlideInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSlideInR object.
*/
static TransitionSlideInR* create(float t, Scene* scene);
/** returns the action that will be performed by the incoming and outgoing scene */
/** Returns the action that will be performed by the incoming and outgoing scene. */
virtual ActionInterval* action(void) override;
CC_CONSTRUCTOR_ACCESS:
@ -326,12 +409,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInR);
};
/** @brief TransitionSlideInB:
/** @class TransitionSlideInB
* @brief TransitionSlideInB:
Slide in the incoming scene from the bottom border.
*/
class CC_DLL TransitionSlideInB : public TransitionSlideInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSlideInB object.
*/
static TransitionSlideInB* create(float t, Scene* scene);
/** returns the action that will be performed by the incoming and outgoing scene */
@ -351,12 +441,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInB);
};
/** @brief TransitionSlideInT:
/** @class TransitionSlideInT
* @brief TransitionSlideInT:
Slide in the incoming scene from the top border.
*/
class CC_DLL TransitionSlideInT : public TransitionSlideInL
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSlideInT object.
*/
static TransitionSlideInT* create(float t, Scene* scene);
/** returns the action that will be performed by the incoming and outgoing scene */
@ -376,12 +473,18 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSlideInT);
};
/**
@brief Shrink the outgoing scene while grow the incoming scene
/** @class TransitionShrinkGrow
* @brief Shrink the outgoing scene while grow the incoming scene
*/
class CC_DLL TransitionShrinkGrow : public TransitionScene , public TransitionEaseScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionShrinkGrow object.
*/
static TransitionShrinkGrow* create(float t, Scene* scene);
//
@ -402,14 +505,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionShrinkGrow);
};
/** @brief TransitionFlipX:
/** @class TransitionFlipX
* @brief TransitionFlipX:
Flips the screen horizontally.
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionFlipX : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionFlipX object.
*/
static TransitionFlipX* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionFlipX object.
*/
static TransitionFlipX* create(float t, Scene* s);
//
@ -429,14 +546,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipX);
};
/** @brief TransitionFlipY:
/** @class TransitionFlipY
* @brief TransitionFlipY:
Flips the screen vertically.
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionFlipY : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionFlipY object.
*/
static TransitionFlipY* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionFlipY object.
*/
static TransitionFlipY* create(float t, Scene* s);
//
@ -456,14 +587,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipY);
};
/** @brief TransitionFlipAngular:
/** @class TransitionFlipAngular
* @brief TransitionFlipAngular:
Flips the screen half horizontally and half vertically.
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionFlipAngular : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionFlipAngular object.
*/
static TransitionFlipAngular* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionFlipAngular object.
*/
static TransitionFlipAngular* create(float t, Scene* s);
//
@ -483,14 +628,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFlipAngular);
};
/** @brief TransitionZoomFlipX:
/** @class TransitionZoomFlipX
* @brief TransitionZoomFlipX:
Flips the screen horizontally doing a zoom out/in
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionZoomFlipX : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionZoomFlipX object.
*/
static TransitionZoomFlipX* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionZoomFlipX object.
*/
static TransitionZoomFlipX* create(float t, Scene* s);
//
@ -510,14 +669,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipX);
};
/** @brief TransitionZoomFlipY:
/** @class TransitionZoomFlipY
* @brief TransitionZoomFlipY:
Flips the screen vertically doing a little zooming out/in
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionZoomFlipY : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionZoomFlipY object.
*/
static TransitionZoomFlipY* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionZoomFlipY object.
*/
static TransitionZoomFlipY* create(float t, Scene* s);
//
@ -537,14 +710,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipY);
};
/** @brief TransitionZoomFlipAngular:
/** @class TransitionZoomFlipAngular
* @brief TransitionZoomFlipAngular:
Flips the screen half horizontally and half vertically doing a little zooming out/in.
The front face is the outgoing scene and the back face is the incoming scene.
*/
class CC_DLL TransitionZoomFlipAngular : public TransitionSceneOriented
{
public:
/** Creates a transition with duration, incoming scene and orientation.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @param o A given orientation.
* @return A autoreleased TransitionZoomFlipAngular object.
*/
static TransitionZoomFlipAngular* create(float t, Scene* s, Orientation o);
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param s A given scene.
* @return A autoreleased TransitionZoomFlipAngular object.
*/
static TransitionZoomFlipAngular* create(float t, Scene* s);
//
@ -564,16 +751,28 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionZoomFlipAngular);
};
/** @brief TransitionFade:
/** @class TransitionFade
* @brief TransitionFade:
Fade out the outgoing scene and then fade in the incoming scene.'''
*/
class CC_DLL TransitionFade : public TransitionScene
{
public:
/** creates the transition with a duration and with an RGB color
* Example: FadeTransition::create(2, scene, Color3B(255,0,0); // red color
*/
/** Creates the transition with a duration and with an RGB color
* Example: FadeTransition::create(2, scene, Color3B(255,0,0); // red color
*
* @param duration Duration time, in seconds.
* @param scene A given scene.
* @param color A given transition color.
* @return A autoreleased TransitionFade object.
*/
static TransitionFade* create(float duration, Scene* scene, const Color3B& color);
/** Creates the transition with a duration.
*
* @param duration Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionFade object.
*/
static TransitionFade* create(float duration, Scene* scene);
/**
@ -604,13 +803,19 @@ private:
};
class RenderTexture;
/**
/** @class TransitionCrossFade
@brief TransitionCrossFade:
Cross fades two scenes using the RenderTexture object.
*/
class CC_DLL TransitionCrossFade : public TransitionScene
{
public :
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionCrossFade object.
*/
static TransitionCrossFade* create(float t, Scene* scene);
//
@ -640,12 +845,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionCrossFade);
};
/** @brief TransitionTurnOffTiles:
/** @class TransitionTurnOffTiles
* @brief TransitionTurnOffTiles:
Turn off the tiles of the outgoing scene in random order
*/
class CC_DLL TransitionTurnOffTiles : public TransitionScene ,public TransitionEaseScene
{
public :
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionTurnOffTiles object.
*/
static TransitionTurnOffTiles* create(float t, Scene* scene);
//
@ -672,14 +884,25 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionTurnOffTiles);
};
/** @brief TransitionSplitCols:
/** @class TransitionSplitCols
* @brief TransitionSplitCols:
The odd columns goes upwards while the even columns goes downwards.
*/
class CC_DLL TransitionSplitCols : public TransitionScene , public TransitionEaseScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSplitCols object.
*/
static TransitionSplitCols* create(float t, Scene* scene);
/** Returns the action that will be performed.
*
* @return The action that will be performed.
*/
virtual ActionInterval* action();
//
@ -705,12 +928,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitCols);
};
/** @brief TransitionSplitRows:
/** @class TransitionSplitRows
* @brief TransitionSplitRows:
The odd rows goes to the left while the even rows goes to the right.
*/
class CC_DLL TransitionSplitRows : public TransitionSplitCols
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionSplitRows object.
*/
static TransitionSplitRows* create(float t, Scene* scene);
//
@ -726,14 +956,26 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitRows);
};
/** @brief TransitionFadeTR:
/** @class TransitionFadeTR
* @brief TransitionFadeTR:
Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
*/
class CC_DLL TransitionFadeTR : public TransitionScene , public TransitionEaseScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionFadeTR object.
*/
static TransitionFadeTR* create(float t, Scene* scene);
/** Returns the action that will be performed with size.
*
* @param size A given size.
* @return The action that will be performed.
*/
virtual ActionInterval* actionWithSize(const Size& size);
//
@ -761,12 +1003,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeTR);
};
/** @brief TransitionFadeBL:
/** @class TransitionFadeBL
* @brief TransitionFadeBL:
Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
*/
class CC_DLL TransitionFadeBL : public TransitionFadeTR
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionFadeBL object.
*/
static TransitionFadeBL* create(float t, Scene* scene);
//
@ -782,12 +1031,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeBL);
};
/** @brief TransitionFadeUp:
/** @class TransitionFadeUp
* @brief TransitionFadeUp:
* Fade the tiles of the outgoing scene from the bottom to the top.
*/
class CC_DLL TransitionFadeUp : public TransitionFadeTR
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionFadeUp object.
*/
static TransitionFadeUp* create(float t, Scene* scene);
//
@ -803,12 +1059,19 @@ private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeUp);
};
/** @brief TransitionFadeDown:
/** @class TransitionFadeDown
* @brief TransitionFadeDown:
* Fade the tiles of the outgoing scene from the top to the bottom.
*/
class CC_DLL TransitionFadeDown : public TransitionFadeTR
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return A autoreleased TransitionFadeDown object.
*/
static TransitionFadeDown* create(float t, Scene* scene);
//

View File

@ -39,8 +39,8 @@ class NodeGrid;
* @{
*/
/**
@brief A transition which peels back the bottom right hand corner of a scene
/** @class TransitionPageTurn
* @brief A transition which peels back the bottom right hand corner of a scene
to transition to the scene beneath it simulating a page turn.
This uses a 3DAction so it's strongly recommended that depth buffering
@ -57,6 +57,11 @@ public:
* Creates a base transition with duration and incoming scene.
* If back is true then the effect is reversed to appear as if the incoming
* scene is being turned from left over the outgoing scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @param backwards If back is true then the effect is reversed to appear as if the incoming scene is being turned from left over the outgoing scene.
* @return An autoreleased TransitionPageTurn object.
*/
static TransitionPageTurn* create(float t,Scene* scene,bool backwards);
@ -66,12 +71,22 @@ public:
virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;
/**
* Creates a base transition with duration and incoming scene.
* If back is true then the effect is reversed to appear as if the incoming
* scene is being turned from left over the outgoing scene.
*/
* Creates a base transition with duration and incoming scene.
* If back is true then the effect is reversed to appear as if the incoming
* scene is being turned from left over the outgoing scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @param backwards If back is true then the effect is reversed to appear as if the incoming scene is being turned from left over the outgoing scene.
* @return True if initialize success.
*/
bool initWithDuration(float t,Scene* scene,bool backwards);
/** Returns the action that will be performed with size.
*
* @param size A given size.
* @return The action that will be performed.
*/
ActionInterval* actionWithSize(const Size& vector);
//

View File

@ -39,9 +39,18 @@ class RenderTexture;
* @addtogroup transition
* @{
*/
/** @class TransitionProgress
* @brief A base class of progress transition.
*/
class CC_DLL TransitionProgress : public TransitionScene
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgress object.
*/
static TransitionProgress* create(float t, Scene* scene);
//
@ -68,12 +77,19 @@ protected:
};
/** TransitionRadialCCW transition.
/** @class TransitionProgressRadialCCW
* @brief TransitionRadialCCW transition.
A counter clock-wise radial transition to the next scene
*/
class CC_DLL TransitionProgressRadialCCW : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressRadialCCW object.
*/
static TransitionProgressRadialCCW* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -92,12 +108,19 @@ protected:
};
/** TransitionRadialCW transition.
A counter clock-wise radial transition to the next scene
/** @class TransitionProgressRadialCW
* @brief TransitionRadialCW transition.
A counter clock-wise radial transition to the next scene.
*/
class CC_DLL TransitionProgressRadialCW : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressRadialCW object.
*/
static TransitionProgressRadialCW* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -115,12 +138,19 @@ protected:
};
/** TransitionProgressHorizontal transition.
/** @class TransitionProgressHorizontal
* @brief TransitionProgressHorizontal transition.
A clock-wise radial transition to the next scene
*/
class CC_DLL TransitionProgressHorizontal : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressHorizontal object.
*/
static TransitionProgressHorizontal* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -137,9 +167,18 @@ protected:
virtual ProgressTimer* progressTimerNodeWithRenderTexture(RenderTexture* texture) override;
};
/** @class TransitionProgressVertical
* @brief TransitionProgressVertical transition.
*/
class CC_DLL TransitionProgressVertical : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressVertical object.
*/
static TransitionProgressVertical* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -156,9 +195,18 @@ protected:
virtual ProgressTimer* progressTimerNodeWithRenderTexture(RenderTexture* texture) override;
};
/** @class TransitionProgressInOut
* @brief TransitionProgressInOut transition.
*/
class CC_DLL TransitionProgressInOut : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressInOut object.
*/
static TransitionProgressInOut* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:
@ -177,9 +225,18 @@ protected:
virtual void setupTransition() override;
};
/** @class TransitionProgressOutIn
* @brief TransitionProgressOutIn transition.
*/
class CC_DLL TransitionProgressOutIn : public TransitionProgress
{
public:
/** Creates a transition with duration and incoming scene.
*
* @param t Duration time, in seconds.
* @param scene A given scene.
* @return An autoreleased TransitionProgressOutIn object.
*/
static TransitionProgressOutIn* create(float t, Scene* scene);
CC_CONSTRUCTOR_ACCESS:

View File

@ -1,5 +0,0 @@
/**@defgroup sprite_nodes
* @ingroup two_d
**/

View File

@ -30,6 +30,9 @@
NS_CC_BEGIN
/**
* Axis Aligned Bounding Box (AABB), usually caculate some rough but fast collision detection.
*/
class CC_DLL AABB
{
@ -90,10 +93,13 @@ public:
void set(const Vec3& min, const Vec3& max);
/**
* reset min and max value.
* Reset min and max value.If you invoke this method, isEmpty() shall return true.
*/
void reset();
/**
* check the AABB object is empty(reset).
*/
bool isEmpty() const;
/**

View File

@ -48,6 +48,7 @@ public:
*/
static AttachNode* create(Bone3D* attachBone);
//override
virtual Mat4 getWorldToNodeTransform() const override;
virtual Mat4 getNodeToWorldTransform() const override;
virtual const Mat4& getNodeToParentTransform() const override;

View File

@ -102,6 +102,9 @@ CC_CONSTRUCTOR_ACCESS:
protected:
/**
* calculate a model matrix which keep orignal translate & scaling but always face to the camera
*/
bool calculateBillbaordTransform();
Mat4 _camWorldMat;

View File

@ -42,7 +42,9 @@ class Data;
class CC_DLL Bundle3D
{
public:
// create a new bundle, destroy it when finish using it
/**
* create a new bundle, destroy it when finish using it
*/
static Bundle3D* createBundle();
static void destroyBundle(Bundle3D* bundle);

View File

@ -129,6 +129,10 @@ struct MeshData
int attribCount;
public:
/**
* Get per vertex size
* @return return the sum of each vertex's all attribute size.
*/
int getPerVertexSize() const
{
int vertexsize = 0;
@ -138,6 +142,10 @@ public:
}
return vertexsize;
}
/**
* Reset the data
*/
void resetData()
{
vertex.clear();

View File

@ -109,6 +109,11 @@ public:
* first read length, then read string text
*/
std::string readString();
/**
* Read the matrix.
* @note the matrix type must be the 4*4 float matrix
*/
bool readMatrix(float* m);
private:

View File

@ -34,6 +34,11 @@
NS_CC_BEGIN
class Camera;
/**
* the frustum is a six-side geometry, usually use the frustum to do fast-culling:
* check a entity whether is a potential visible entity
*/
class CC_DLL Frustum
{
friend class Camera;

View File

@ -196,7 +196,7 @@ void Mesh::setSkin(MeshSkin* skin)
CC_SAFE_RETAIN(skin);
CC_SAFE_RELEASE(_skin);
_skin = skin;
calcuateAABB();
calculateAABB();
}
}
@ -207,7 +207,7 @@ void Mesh::setMeshIndexData(MeshIndexData* subMesh)
CC_SAFE_RETAIN(subMesh);
CC_SAFE_RELEASE(_meshIndexData);
_meshIndexData = subMesh;
calcuateAABB();
calculateAABB();
bindMeshCommand();
}
}
@ -223,7 +223,7 @@ void Mesh::setGLProgramState(GLProgramState* glProgramState)
}
}
void Mesh::calcuateAABB()
void Mesh::calculateAABB()
{
if (_meshIndexData)
{

View File

@ -110,11 +110,20 @@ CC_CONSTRUCTOR_ACCESS:
Mesh();
virtual ~Mesh();
/**
* Get the default GL program.
*/
GLProgram* getDefaultGLProgram(bool textured);
/**
* Set the default GL program.
*/
void setGLProgramState(GLProgramState* glProgramState);
/**
* Get the MeshCommand.
*/
MeshCommand& getMeshCommand() { return _meshCommand; }
/**skin setter*/
@ -124,8 +133,15 @@ CC_CONSTRUCTOR_ACCESS:
/**name setter*/
void setName(const std::string& name) { _name = name; }
void calcuateAABB();
/**
* calculate the AABB of the mesh
* @note the AABB is in the local space, not the world space
*/
void calculateAABB();
/**
* Bind to the MeshCommand
*/
void bindMeshCommand();
protected:
Texture2D* _texture; //texture that submesh is using

View File

@ -43,6 +43,10 @@ NS_CC_BEGIN
class MeshVertexData;
/**
* the MeshIndexData class.
* @brief the MeshIndexData contain all of the indices data which mesh need.
*/
class MeshIndexData : public Ref
{
public:
@ -84,6 +88,10 @@ protected:
friend class Sprite3D;
};
/**
* the MeshVertexData class.
* @brief the MeshIndexData contain all of the vertices data which mesh need.
*/
class MeshVertexData : public Ref
{
friend class Sprite3D;

View File

@ -29,6 +29,10 @@
NS_CC_BEGIN
/**
* Oritened Bounding Box(OBB)
* @brief the OBB is similar to the AABB but the bounding box has the same direction as Sprite3D. so it's collistion detection more precise than AABB
*/
class CC_DLL OBB
{
public:

View File

@ -16,9 +16,16 @@
NS_CC_BEGIN
/**
* .obj file Loader
**/
class ObjLoader
{
public:
/**
* model's material struct
**/
typedef struct
{
std::string name;
@ -41,11 +48,17 @@ public:
std::map<std::string, std::string> unknown_parameter;
} material_t;
/**
* model's indices struct
**/
typedef struct
{
std::vector<unsigned short> indices;
} mesh_t;
/**
* model's shape struct
**/
typedef struct
{
std::string name;
@ -53,6 +66,9 @@ public:
mesh_t mesh;
} shape_t;
/**
* model's shapes struct
**/
typedef struct
{
std::vector<float> positions;
@ -70,11 +86,13 @@ public:
}
}shapes_t;
/// Loads .obj from a file.
/// 'shapes' will be filled with parsed shape data
/// The function returns error string.
/// Returns empty string when loading .obj success.
/// 'mtl_basepath' is optional, and used for base path for .mtl file.
/**
* Loads .obj from a file.
* @param shapes will be filled with parsed shape data
* @param filename the .obj file path .
* @param mtl_basepath It's optional, and used for base path for .mtl file
* @return The function returns error string, return empty string when loading .obj success.
*/
static std::string LoadObj(
shapes_t& shapes, // [output]
const char* filename,

View File

@ -37,6 +37,9 @@ enum class PointSide
BEHIND_PLANE,
};
/**
* Defines plane
**/
class CC_DLL Plane
{
public:
@ -96,8 +99,8 @@ public:
PointSide getSide(const Vec3& point) const;
protected:
Vec3 _normal;
float _dist;
Vec3 _normal; // the normal line of the plane
float _dist; // original displacement of the normal
};
NS_CC_END

View File

@ -32,6 +32,9 @@
NS_CC_BEGIN
/**
* Ray is a line with one end. usually use it to check intersects with some object,such as Plane, OBB, AABB
**/
class CC_DLL Ray
{
public:

View File

@ -118,7 +118,10 @@ public:
protected:
/**
* the BoneBlendState struct
* @brief store the transformation and weight for bone blending
*/
struct BoneBlendState
{
Vec3 localTranslate;

View File

@ -233,6 +233,10 @@ protected:
};
///////////////////////////////////////////////////////
/**
* Sprite3DCache
* @brief the cache data of Sprite3D, use to speed up Sprite3D::create
*/
class CC_DLL Sprite3DCache
{
public:
@ -256,13 +260,17 @@ public:
/**get & destroy*/
static Sprite3DCache* getInstance();
static void destroyInstance();
/**get the SpriteData struct*/
Sprite3DData* getSpriteData(const std::string& key) const;
/**add the SpriteData into Sprite3D by given the specified key*/
bool addSprite3DData(const std::string& key, Sprite3DData* spritedata);
/**remove the SpriteData from Sprite3D by given the specified key*/
void removeSprite3DData(const std::string& key);
/**remove all the SpriteData from Sprite3D*/
void removeAllSprite3DData();
CC_CONSTRUCTOR_ACCESS:

View File

@ -52,6 +52,7 @@ NS_CC_BEGIN
* @class AudioProfile
*
* @brief
* @js NA
*/
class EXPORT_DLL AudioProfile
{
@ -80,6 +81,7 @@ class AudioEngineImpl;
* @brief Offers a interface to play audio.
*
* @note Make sure to call AudioEngine::end() when the audio engine is not needed anymore to release resources.
* @js NA
*/
class EXPORT_DLL AudioEngine

View File

@ -50,6 +50,7 @@ namespace CocosDenshion {
* @brief Offers a very simple interface to play background music & sound effects.
*
* @note Make sure to call SimpleAudioEngine::end() when the sound engine is not needed anymore to release allocated resources.
* @js cc.audioEngine
*/
class EXPORT_DLL SimpleAudioEngine
@ -57,6 +58,7 @@ class EXPORT_DLL SimpleAudioEngine
public:
/**
* Returns a shared instance of the SimpleAudioEngine.
* @js NA
*/
static SimpleAudioEngine* getInstance();
@ -78,7 +80,7 @@ public:
* Preload background music.
*
* @param filePath The path of the background music file.
* @js preloadMusic
* @js NA
* @lua preloadMusic
*/
virtual void preloadBackgroundMusic(const char* filePath);
@ -235,6 +237,7 @@ public:
* The compressed audio will be decoded to wave, then written into an internal buffer in SimpleAudioEngine.
*
* @param filePath The path of the effect file.
* @js NA
*/
virtual void preloadEffect(const char* filePath);

View File

@ -39,18 +39,22 @@ NS_CC_BEGIN
* @addtogroup global
* @{
*/
/**
@brief Configuration contains some openGL variables
@since v0.99.0
/** @class Configuration
* @brief Configuration contains some openGL variables
* @since v0.99.0
*/
class CC_DLL Configuration : public Ref
{
public:
/** returns a shared instance of Configuration */
/** Returns a shared instance of Configuration.
*
* @return An autoreleased Configuration object.
*/
static Configuration *getInstance();
/** purge the shared instance of Configuration */
/** Purge the shared instance of Configuration.
*/
static void destroyInstance();
/** @deprecated Use getInstance() instead */
@ -60,90 +64,147 @@ public:
CC_DEPRECATED_ATTRIBUTE static void purgeConfiguration();
public:
/**
/** Destructor
* @js NA
* @lua NA
*/
virtual ~Configuration();
/** OpenGL Max texture size. */
/** OpenGL Max texture size.
*
* @return The OpenGL Max texture size.
*/
int getMaxTextureSize() const;
/** OpenGL Max Modelview Stack Depth. */
/** OpenGL Max Modelview Stack Depth.
*
* @return The OpenGL Max Modelview Stack Depth.
*/
int getMaxModelviewStackDepth() const;
/** returns the maximum texture units
@since v2.0.0
/** Returns the maximum texture units.
*
* @return The maximum texture units.
* @since v2.0.0
*/
int getMaxTextureUnits() const;
/** Whether or not the GPU supports NPOT (Non Power Of Two) textures.
OpenGL ES 2.0 already supports NPOT (iOS).
@since v0.99.2
*
* @return Is true if supports NPOT.
* @since v0.99.2
*/
bool supportsNPOT() const;
/** Whether or not PVR Texture Compressed is supported */
/** Whether or not PVR Texture Compressed is supported.
*
* @return Is true if supports PVR Texture Compressed.
*/
bool supportsPVRTC() const;
/** Whether or not ETC Texture Compressed is supported */
/** Whether or not ETC Texture Compressed is supported.
*
*
* @return Is true if supports ETC Texture Compressed.
*/
bool supportsETC() const;
/** Whether or not S3TC Texture Compressed is supported */
/** Whether or not S3TC Texture Compressed is supported.
*
* @return Is true if supports S3TC Texture Compressed.
*/
bool supportsS3TC() const;
/** Whether or not ATITC Texture Compressed is supported */
/** Whether or not ATITC Texture Compressed is supported.
*
* @return Is true if supports ATITC Texture Compressed.
*/
bool supportsATITC() const;
/** Whether or not BGRA8888 textures are supported.
@since v0.99.2
*
* @return Is true if supports BGRA8888 textures.
* @since v0.99.2
*/
bool supportsBGRA8888() const;
/** Whether or not glDiscardFramebufferEXT is supported
@since v0.99.2
/** Whether or not glDiscardFramebufferEXT is supported.
* @return Is true if supports glDiscardFramebufferEXT.
* @since v0.99.2
*/
bool supportsDiscardFramebuffer() const;
/** Whether or not shareable VAOs are supported.
@since v2.0.0
*
* @return Is true if supports shareable VAOs.
* @since v2.0.0
*/
bool supportsShareableVAO() const;
/** Max support directional light in shader, for Sprite3D
@since v3.3
/** Max support directional light in shader, for Sprite3D.
*
* @return Maximum supports directional light in shader.
* @since v3.3
*/
int getMaxSupportDirLightInShader() const;
/** Max support point light in shader, for Sprite3D
*since v3.3
/** Max support point light in shader, for Sprite3D.
*
* @return Maximum supports point light in shader.
* @since v3.3
*/
int getMaxSupportPointLightInShader() const;
/** Max support spot light in shader, for Sprite3D
*since v3.3
/** Max support spot light in shader, for Sprite3D.
*
* @return Maximum supports spot light in shader.
* @since v3.3
*/
int getMaxSupportSpotLightInShader() const;
/** returns whether or not an OpenGL is supported */
/** Returns whether or not an OpenGL is supported.
*
* @param searchName A given search name.
* @return Is true if an OpenGL is supported.
*/
bool checkForGLExtension(const std::string &searchName) const;
/** Initialize method.
*
* @return Is true if initialize success.
*/
bool init();
/** returns the value of a given key as a double */
/** Returns the value of a given key as a double.
*
* @param key A given key.
* @param defaultValue if not find the value, return the defaultValue.
* @return
*/
const Value& getValue(const std::string& key, const Value& defaultValue = Value::Null) const;
/** sets a new key/value pair in the configuration dictionary */
/** Sets a new key/value pair in the configuration dictionary.
*
* @param key A given key.
* @param value A given value.
*/
void setValue(const std::string& key, const Value& value);
/** returns the Configuration info */
/** Returns the Configuration info.
*
* @return The Configuration info.
*/
std::string getInfo() const;
/** gathers OpenGL / GPU information */
/** Gathers OpenGL / GPU information.
*/
void gatherGPUInfo();
/** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */
/** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added.
*
* @param filename Config file name.
*/
void loadConfigFile(const std::string& filename);
private:

View File

@ -41,6 +41,7 @@ class EventDispatcher;
/**
* @class Controller
* @brief A Controller object represents a connected physical game controller.
* @js NA
*/
class Controller
{

View File

@ -36,43 +36,43 @@ NS_CC_BEGIN
*/
/**
@brief Returns a Core Graphics rectangle structure corresponding to the data in a given string.
@param pszContent A string object whose contents are of the form "{{x,y},{w, h}}",
where x is the x coordinate, y is the y coordinate, w is the width, and h is the height.
These components can represent integer or float values.
An example of a valid string is "{{3,2},{4,5}}".
The string is not localized, so items are always separated with a comma.
@return A Core Graphics structure that represents a rectangle.
If the string is not well-formed, the function returns Rect::ZERO.
*/
* @brief Returns a Core Graphics rectangle structure corresponding to the data in a given string.
* @param pszContent A string object whose contents are of the form "{{x,y},{w, h}}",
* where x is the x coordinate, y is the y coordinate, w is the width, and h is the height.
* These components can represent integer or float values.
* An example of a valid string is "{{3,2},{4,5}}".
* The string is not localized, so items are always separated with a comma.
* @return A Core Graphics structure that represents a rectangle.
* If the string is not well-formed, the function returns Rect::ZERO.
*/
Rect CC_DLL RectFromString(const std::string& str);
/**
@brief Returns a Core Graphics point structure corresponding to the data in a given string.
@param pszContent A string object whose contents are of the form "{x,y}",
where x is the x coordinate and y is the y coordinate.
The x and y values can represent integer or float values.
An example of a valid string is "{3.0,2.5}".
The string is not localized, so items are always separated with a comma.
@return A Core Graphics structure that represents a point.
If the string is not well-formed, the function returns Vec2::ZERO.
*/
* @brief Returns a Core Graphics point structure corresponding to the data in a given string.
* @param pszContent A string object whose contents are of the form "{x,y}",
* where x is the x coordinate and y is the y coordinate.
* The x and y values can represent integer or float values.
* An example of a valid string is "{3.0,2.5}".
* The string is not localized, so items are always separated with a comma.
* @return A Core Graphics structure that represents a point.
* If the string is not well-formed, the function returns Vec2::ZERO.
*/
Vec2 CC_DLL PointFromString(const std::string& str);
/**
@brief Returns a Core Graphics size structure corresponding to the data in a given string.
@param pszContent A string object whose contents are of the form "{w, h}",
where w is the width and h is the height.
The w and h values can be integer or float values.
An example of a valid string is "{3.0,2.5}".
The string is not localized, so items are always separated with a comma.
@return A Core Graphics structure that represents a size.
If the string is not well-formed, the function returns Size::ZERO.
*/
* @brief Returns a Core Graphics size structure corresponding to the data in a given string.
* @param pszContent A string object whose contents are of the form "{w, h}",
* where w is the width and h is the height.
* The w and h values can be integer or float values.
* An example of a valid string is "{3.0,2.5}".
* The string is not localized, so items are always separated with a comma.
* @return A Core Graphics structure that represents a size.
* If the string is not well-formed, the function returns Size::ZERO.
*/
Size CC_DLL SizeFromString(const std::string& str);
// end of data_structure group
/// @}
/** @} */
NS_CC_END

View File

@ -209,7 +209,6 @@ public:
/** 'update' the scheduler.
* You should NEVER call this method, unless you know what you are doing.
* @js NA
* @lua NA
*/
void update(float dt);
@ -330,7 +329,6 @@ public:
This also includes the "update" selector.
@param target The target to be unscheduled.
@since v0.99.3
@js unscheduleCallbackForTarget
@lua NA
*/
void unscheduleAllForTarget(void *target);
@ -400,7 +398,6 @@ public:
* @param target The target to be checked.
* @return True if the target is paused, false if not.
* @since v1.0.0
* @js isTargetPaused(var jsObject)
* @lua NA
*/
bool isTargetPaused(void *target);
@ -430,6 +427,7 @@ public:
This function is thread safe.
@param function The function to be run in cocos2d thread.
@since v3.0
@js NA
*/
void performFunctionInCocosThread( const std::function<void()> &function);
@ -445,6 +443,7 @@ public:
delay is the amount of time the action will wait before it'll start
@deprecated Please use `Scheduler::schedule` instead.
@since v0.99.3, repeat and delay added in v1.1
@js NA
*/
CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused)
{
@ -453,6 +452,7 @@ public:
/** Calls scheduleSelector with CC_REPEAT_FOREVER and a 0 delay.
* @deprecated Please use `Scheduler::schedule` instead.
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused)
{
@ -472,12 +472,14 @@ public:
If you want to unschedule the "update", use unscheudleUpdateForTarget.
@deprecated Please use 'Scheduler::unschedule' instead.
@since v0.99.3
@js NA
*/
CC_DEPRECATED_ATTRIBUTE void unscheduleSelector(SEL_SCHEDULE selector, Ref *target) { unschedule(selector, target); };
/** Checks whether a selector for a given taget is scheduled.
@deprecated Please use 'Scheduler::isScheduled' instead.
@since v0.99.3
@js NA
*/
CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduled(selector, target); };
@ -494,6 +496,7 @@ protected:
The lower the priority, the earlier it is called.
@note This method is only for internal use.
@since v3.0
@js _schedulePerFrame
*/
void schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused);

View File

@ -36,37 +36,68 @@ NS_CC_BEGIN
* @{
*/
/** @class Touch
* @brief Encapsulates the Touch information, such as touch point, id and so on,
and provides the methods that commonly used.
*/
class CC_DLL Touch : public Ref
{
public:
/** how the touches are dispathced */
/** Dispatch mode, how the touches are dispathced. */
enum class DispatchMode {
/** All at once */
ALL_AT_ONCE,
/** one by one */
ONE_BY_ONE,
ALL_AT_ONCE, /** All at once. */
ONE_BY_ONE, /** One by one. */
};
/** Constructor.
*/
Touch()
: _id(0),
_startPointCaptured(false)
{}
/** returns the current touch location in OpenGL coordinates */
/** Returns the current touch location in OpenGL coordinates.
*
* @return The current touch location in OpenGL coordinates.
*/
Vec2 getLocation() const;
/** returns the previous touch location in OpenGL coordinates */
/** Returns the previous touch location in OpenGL coordinates.
*
* @return The previous touch location in OpenGL coordinates.
*/
Vec2 getPreviousLocation() const;
/** returns the start touch location in OpenGL coordinates */
/** Returns the start touch location in OpenGL coordinates.
*
* @return The start touch location in OpenGL coordinates.
*/
Vec2 getStartLocation() const;
/** returns the delta of 2 current touches locations in screen coordinates */
/** Returns the delta of 2 current touches locations in screen coordinates.
*
* @return The delta of 2 current touches locations in screen coordinates.
*/
Vec2 getDelta() const;
/** returns the current touch location in screen coordinates */
/** Returns the current touch location in screen coordinates.
*
* @return The current touch location in screen coordinates.
*/
Vec2 getLocationInView() const;
/** returns the previous touch location in screen coordinates */
/** Returns the previous touch location in screen coordinates.
*
* @return The previous touch location in screen coordinates.
*/
Vec2 getPreviousLocationInView() const;
/** returns the start touch location in screen coordinates */
/** Returns the start touch location in screen coordinates.
*
* @return The start touch location in screen coordinates.
*/
Vec2 getStartLocationInView() const;
/** Set the touch infomation. It always used to monitor touch event.
*
* @param id A given id
* @param x A given x coordinate.
* @param y A given y coordinate.
*/
void setTouchInfo(int id, float x, float y)
{
_id = id;
@ -80,9 +111,11 @@ public:
_prevPoint = _point;
}
}
/**
/** Get touch id.
* @js getId
* @lua getId
*
* @return The id of touch.
*/
int getID() const
{

View File

@ -43,94 +43,169 @@ CC_DLL extern const ValueVector ValueVectorNull;
CC_DLL extern const ValueMap ValueMapNull;
CC_DLL extern const ValueMapIntKey ValueMapIntKeyNull;
/**
* This class is provide as a wrapper of basic types, such as int and bool.
*/
class CC_DLL Value
{
public:
/** A predefined Value that has not value. */
static const Value Null;
/** Default constructor. */
Value();
/** Create a Value by an unsigned char value. */
explicit Value(unsigned char v);
/** Create a Value by an integer value. */
explicit Value(int v);
/** Create a Value by a float value. */
explicit Value(float v);
/** Create a Value by a double value. */
explicit Value(double v);
/** Create a Value by a bool value. */
explicit Value(bool v);
/** Create a Value by a char pointer. It will copy the chars internally. */
explicit Value(const char* v);
/** Create a Value by a string. */
explicit Value(const std::string& v);
/** Create a Value by a ValueVector object. */
explicit Value(const ValueVector& v);
/** Create a Value by a ValueVector object. It will use std::move internally. */
explicit Value(ValueVector&& v);
/** Create a Value by a ValueMap object. */
explicit Value(const ValueMap& v);
explicit Value(ValueMap&& v);
/** Create a Value by a ValueMap object. It will use std::move internally. */
explicit Value(ValueMap&& v);
/** Create a Value by a ValueMapIntKey object. */
explicit Value(const ValueMapIntKey& v);
/** Create a Value by a ValueMapIntKey object. It will use std::move internally. */
explicit Value(ValueMapIntKey&& v);
/** Create a Value by anthoer Value object. */
Value(const Value& other);
/** Create a Value by a Value object. It will use std::move internally. */
Value(Value&& other);
/** Destructor. */
~Value();
// assignment operator
/** Assignment operator, assign from Value to Value. */
Value& operator= (const Value& other);
/** Assignment operator, assign from Value to Value. It will use std::move internally. */
Value& operator= (Value&& other);
/** Assignment operator, assign from unsigned char to Value. */
Value& operator= (unsigned char v);
/** Assignment operator, assign from integer to Value. */
Value& operator= (int v);
/** Assignment operator, assign from float to Value. */
Value& operator= (float v);
/** Assignment operator, assign from double to Value. */
Value& operator= (double v);
/** Assignment operator, assign from bool to Value. */
Value& operator= (bool v);
/** Assignment operator, assign from char* to Value. */
Value& operator= (const char* v);
/** Assignment operator, assign from string to Value. */
Value& operator= (const std::string& v);
/** Assignment operator, assign from ValueVector to Value. */
Value& operator= (const ValueVector& v);
/** Assignment operator, assign from ValueVector to Value. */
Value& operator= (ValueVector&& v);
/** Assignment operator, assign from ValueMap to Value. */
Value& operator= (const ValueMap& v);
Value& operator= (ValueMap&& v);
/** Assignment operator, assign from ValueMap to Value. It will use std::move internally. */
Value& operator= (ValueMap&& v);
/** Assignment operator, assign from ValueMapIntKey to Value. */
Value& operator= (const ValueMapIntKey& v);
/** Assignment operator, assign from ValueMapIntKey to Value. It will use std::move internally. */
Value& operator= (ValueMapIntKey&& v);
// equal operator
/** != operator overloading */
bool operator!= (const Value& v);
/** != operator overloading */
bool operator!= (const Value& v) const;
/** == operator overloading */
bool operator== (const Value& v);
/** == operator overloading */
bool operator== (const Value& v) const;
/** Gets as a byte value. Will convert to unsigned char if possible, or will trigger assert error. */
unsigned char asByte() const;
/** Gets as an integer value. Will convert to integer if possible, or will trigger assert error. */
int asInt() const;
/** Gets as a float value. Will convert to float if possible, or will trigger assert error. */
float asFloat() const;
/** Gets as a double value. Will convert to double if possible, or will trigger assert error. */
double asDouble() const;
/** Gets as a bool value. Will convert to bool if possible, or will trigger assert error. */
bool asBool() const;
/** Gets as a string value. Will convert to string if possible, or will trigger assert error. */
std::string asString() const;
/** Gets as a ValueVector reference. Will convert to ValueVector if possible, or will trigger assert error. */
ValueVector& asValueVector();
/** Gets as a const ValueVector reference. Will convert to ValueVector if possible, or will trigger assert error. */
const ValueVector& asValueVector() const;
/** Gets as a ValueMap reference. Will convert to ValueMap if possible, or will trigger assert error. */
ValueMap& asValueMap();
/** Gets as a const ValueMap reference. Will convert to ValueMap if possible, or will trigger assert error. */
const ValueMap& asValueMap() const;
/** Gets as a ValueMapIntKey reference. Will convert to ValueMapIntKey if possible, or will trigger assert error. */
ValueMapIntKey& asIntKeyMap();
/** Gets as a const ValueMapIntKey reference. Will convert to ValueMapIntKey if possible, or will trigger assert error. */
const ValueMapIntKey& asIntKeyMap() const;
/**
* Checks if the Value is null.
* @return True if the Value is null, false if not.
*/
inline bool isNull() const { return _type == Type::NONE; }
/** Value type wrapped by Value. */
enum class Type
{
/// no value is wrapped, an empty Value
NONE = 0,
/// wrap byte
BYTE,
/// wrap integer
INTEGER,
/// wrap float
FLOAT,
/// wrap double
DOUBLE,
/// wrap bool
BOOLEAN,
/// wrap string
STRING,
/// wrap vector
VECTOR,
/// wrap ValueMap
MAP,
/// wrap ValueMapIntKey
INT_KEY_MAP
};
inline Type getType() const { return _type; };
/** Gets the value type. */
inline Type getType() const { return _type; }
/** Gets the description of the class. */
std::string getDescription() const;
private:

View File

@ -31,245 +31,228 @@ THE SOFTWARE.
#include "platform/CCPlatformConfig.h"
/**
@file
cocos2d (cc) configuration file
* @file
* cocos2d (cc) configuration file.
*/
/** @def CC_ENABLE_STACKABLE_ACTIONS
If enabled, actions that alter the position property (eg: MoveBy, JumpBy, BezierBy, etc..) will be stacked.
If you run 2 or more 'position' actions at the same time on a node, then end position will be the sum of all the positions.
If disabled, only the last run action will take effect.
Enabled by default. Disable to be compatible with v2.0 and older versions.
@since v2.1
* If enabled, actions that alter the position property (eg: MoveBy, JumpBy, BezierBy, etc..) will be stacked.
* If you run 2 or more 'position' actions at the same time on a node, then end position will be the sum of all the positions.
* If disabled, only the last run action will take effect.
* Enabled by default. Disable to be compatible with v2.0 and older versions.
* @since v2.1
*/
#ifndef CC_ENABLE_STACKABLE_ACTIONS
#define CC_ENABLE_STACKABLE_ACTIONS 1
#endif
/** @def CC_ENABLE_GL_STATE_CACHE
If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
In order to use them, you have to use the following functions, instead of the the GL ones:
- ccGLUseProgram() instead of glUseProgram()
- GL::deleteProgram() instead of glDeleteProgram()
- GL::blendFunc() instead of glBlendFunc()
* If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
* In order to use them, you have to use the following functions, instead of the the GL ones:
* - ccGLUseProgram() instead of glUseProgram().
* - GL::deleteProgram() instead of glDeleteProgram().
* - GL::blendFunc() instead of glBlendFunc().
If this functionality is disabled, then ccGLUseProgram(), GL::deleteProgram(), GL::blendFunc() will call the GL ones, without using the cache.
* If this functionality is disabled, then ccGLUseProgram(), GL::deleteProgram(), GL::blendFunc() will call the GL ones, without using the cache.
It is recommended to enable whenever possible to improve speed.
If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on.
* It is recommended to enable whenever possible to improve speed.
* If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on.
Default value: Enabled by default
* Default value: Enabled by default
@since v2.0.0
* @since v2.0.0
*/
#ifndef CC_ENABLE_GL_STATE_CACHE
#define CC_ENABLE_GL_STATE_CACHE 1
#endif
/** @def CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
If enabled, the texture coordinates will be calculated by using this formula:
- texCoord.left = (rect.origin.x*2+1) / (texture.wide*2);
- texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2);
* If enabled, the texture coordinates will be calculated by using this formula:
* - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2);
* - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2);
The same for bottom and top.
* The same for bottom and top.
This formula prevents artifacts by using 99% of the texture.
The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool.
* This formula prevents artifacts by using 99% of the texture.
* The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool.
Affected nodes:
- Sprite / SpriteBatchNode and subclasses: LabelBMFont, TMXTiledMap
- LabelAtlas
- QuadParticleSystem
- TileMap
To enabled set it to 1. Disabled by default.
@since v0.99.5
*/
* Affected nodes:
* - Sprite / SpriteBatchNode and subclasses: LabelBMFont, TMXTiledMap.
* - LabelAtlas.
* - QuadParticleSystem.
* - TileMap.
* To enabled set it to 1. Disabled by default.
* @since v0.99.5
*/
#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0
#endif
/** @def CC_DIRECTOR_FPS_INTERVAL
Seconds between FPS updates.
0.5 seconds, means that the FPS number will be updated every 0.5 seconds.
Having a bigger number means a more reliable FPS
* Seconds between FPS updates.
* 0.5 seconds, means that the FPS number will be updated every 0.5 seconds.
* Having a bigger number means a more reliable FPS.
Default value: 0.1f
* Default value: 0.1f
*/
#ifndef CC_DIRECTOR_STATS_INTERVAL
#define CC_DIRECTOR_STATS_INTERVAL (0.1f)
#endif
/** @def CC_DIRECTOR_FPS_POSITION
Position of the FPS
* Position of the FPS.
Default: 0,0 (bottom-left corner)
* Default: 0,0 (bottom-left corner).
*/
#ifndef CC_DIRECTOR_FPS_POSITION
#define CC_DIRECTOR_FPS_POSITION Vec2(0,0)
#endif
/** @def CC_DIRECTOR_DISPATCH_FAST_EVENTS
If enabled, and only when it is used with FastDirector, the main loop will wait 0.04 seconds to
dispatch all the events, even if there are not events to dispatch.
If your game uses lot's of events (eg: touches) it might be a good idea to enable this feature.
Otherwise, it is safe to leave it disabled.
* If enabled, and only when it is used with FastDirector, the main loop will wait 0.04 seconds to
* dispatch all the events, even if there are not events to dispatch.
* If your game uses lot's of events (eg: touches) it might be a good idea to enable this feature.
* Otherwise, it is safe to leave it disabled.
To enable set it to 1. Disabled by default.
* To enable set it to 1. Disabled by default.
@warning This feature is experimental
* @warning This feature is experimental.
*/
#ifndef CC_DIRECTOR_DISPATCH_FAST_EVENTS
#define CC_DIRECTOR_DISPATCH_FAST_EVENTS 0
#endif
/** @def CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
If enabled, cocos2d-mac will run on the Display Link thread. If disabled cocos2d-mac will run in its own thread.
If enabled, the images will be drawn at the "correct" time, but the events might not be very responsive.
If disabled, some frames might be skipped, but the events will be dispatched as they arrived.
To enable set it to a 1, to disable it set to 0. Enabled by default.
Only valid for cocos2d-mac. Not supported on cocos2d-ios.
*/
* If enabled, cocos2d-mac will run on the Display Link thread. If disabled cocos2d-mac will run in its own thread.
* If enabled, the images will be drawn at the "correct" time, but the events might not be very responsive.
* If disabled, some frames might be skipped, but the events will be dispatched as they arrived.
* To enable set it to a 1, to disable it set to 0. Enabled by default.
* Only valid for cocos2d-mac. Not supported on cocos2d-ios.
*/
#ifndef CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
#define CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD 1
#endif
/** @def CC_NODE_RENDER_SUBPIXEL
If enabled, the Node objects (Sprite, Label,etc) will be able to render in subpixels.
If disabled, integer pixels will be used.
To enable set it to 1. Enabled by default.
* If enabled, the Node objects (Sprite, Label,etc) will be able to render in subpixels.
* If disabled, integer pixels will be used.
* To enable set it to 1. Enabled by default.
*/
#ifndef CC_NODE_RENDER_SUBPIXEL
#define CC_NODE_RENDER_SUBPIXEL 1
#endif
/** @def CC_SPRITEBATCHNODE_RENDER_SUBPIXEL
If enabled, the Sprite objects rendered with SpriteBatchNode will be able to render in subpixels.
If disabled, integer pixels will be used.
To enable set it to 1. Enabled by default.
* If enabled, the Sprite objects rendered with SpriteBatchNode will be able to render in subpixels.
* If disabled, integer pixels will be used.
* To enable set it to 1. Enabled by default.
*/
#ifndef CC_SPRITEBATCHNODE_RENDER_SUBPIXEL
#define CC_SPRITEBATCHNODE_RENDER_SUBPIXEL 1
#endif
/** @def CC_TEXTURE_ATLAS_USE_VAO
By default, TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).
Apple recommends its usage but they might consume a lot of memory, specially if you use many of them.
So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it.
To disable it set it to 0. Enabled by default.
* By default, TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).
* Apple recommends its usage but they might consume a lot of memory, specially if you use many of them.
* So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it.
* To disable it set it to 0. Enabled by default.
*/
#ifndef CC_TEXTURE_ATLAS_USE_VAO
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#define CC_TEXTURE_ATLAS_USE_VAO 1
#else
/* Some Windows display adapter driver cannot support VAO. */
/* Some android devices cannot support VAO very well, so we disable it by default for android platform. */
/* Blackberry also doesn't support this feature. */
/* Some Windows display adapter driver cannot support VAO.
* Some android devices cannot support VAO very well, so we disable it by default for android platform.
* Blackberry also doesn't support this feature.
*/
#define CC_TEXTURE_ATLAS_USE_VAO 0
#endif
#endif
/** @def CC_USE_LA88_LABELS
If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for LabelTTF objects.
If it is disabled, it will use A8 (Alpha 8-bit textures).
LA88 textures are 6% faster than A8 textures, but they will consume 2x memory.
This feature is enabled by default.
@since v0.99.5
* If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for LabelTTF objects.
* If it is disabled, it will use A8 (Alpha 8-bit textures).
* LA88 textures are 6% faster than A8 textures, but they will consume 2x memory.
* This feature is enabled by default.
* @since v0.99.5
*/
#ifndef CC_USE_LA88_LABELS
#define CC_USE_LA88_LABELS 1
#endif
/** @def CC_SPRITE_DEBUG_DRAW
If enabled, all subclasses of Sprite will draw a bounding box
Useful for debugging purposes only. It is recommended to leave it disabled.
To enable set it to a value different than 0. Disabled by default:
0 -- disabled
1 -- draw bounding box
2 -- draw texture box
*/
* If enabled, all subclasses of Sprite will draw a bounding box.
* Useful for debugging purposes only. It is recommended to leave it disabled.
* To enable set it to a value different than 0. Disabled by default:
* 0 -- disabled
* 1 -- draw bounding box
* 2 -- draw texture box
*/
#ifndef CC_SPRITE_DEBUG_DRAW
#define CC_SPRITE_DEBUG_DRAW 0
#endif
/** @def CC_SPRITEBATCHNODE_DEBUG_DRAW
If enabled, all subclasses of Sprite that are rendered using an SpriteBatchNode draw a bounding box.
Useful for debugging purposes only. It is recommended to leave it disabled.
To enable set it to a value different than 0. Disabled by default.
*/
* If enabled, all subclasses of Sprite that are rendered using an SpriteBatchNode draw a bounding box.
* Useful for debugging purposes only. It is recommended to leave it disabled.
* To enable set it to a value different than 0. Disabled by default.
*/
#ifndef CC_SPRITEBATCHNODE_DEBUG_DRAW
#define CC_SPRITEBATCHNODE_DEBUG_DRAW 0
#endif
/** @def CC_LABELBMFONT_DEBUG_DRAW
If enabled, all subclasses of LabelBMFont will draw a bounding box
Useful for debugging purposes only. It is recommended to leave it disabled.
To enable set it to a value different than 0. Disabled by default.
*/
* If enabled, all subclasses of LabelBMFont will draw a bounding box.
* Useful for debugging purposes only. It is recommended to leave it disabled.
* To enable set it to a value different than 0. Disabled by default.
*/
#ifndef CC_LABELBMFONT_DEBUG_DRAW
#define CC_LABELBMFONT_DEBUG_DRAW 0
#endif
/** @def CC_LABELATLAS_DEBUG_DRAW
If enabled, all subclasses of LabeltAtlas will draw a bounding box
Useful for debugging purposes only. It is recommended to leave it disabled.
To enable set it to a value different than 0. Disabled by default.
* If enabled, all subclasses of LabeltAtlas will draw a bounding box
* Useful for debugging purposes only. It is recommended to leave it disabled.
* To enable set it to a value different than 0. Disabled by default.
*/
#ifndef CC_LABELATLAS_DEBUG_DRAW
#define CC_LABELATLAS_DEBUG_DRAW 0
#endif
/** @def CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
If enabled (in conjunction with assertion macros) will verify on Node destruction that the node being destroyed has no event
listeners still associated with it in the event dispatcher. This can be used to track down problems where the event dispatch
system has dangling pointers to destroyed nodes.
Note: event listener verification will always be disabled in builds where assertions are disabled regardless of this setting.
* If enabled (in conjunction with assertion macros) will verify on Node destruction that the node being destroyed has no event
* listeners still associated with it in the event dispatcher. This can be used to track down problems where the event dispatch
* system has dangling pointers to destroyed nodes.
* Note: event listener verification will always be disabled in builds where assertions are disabled regardless of this setting.
*/
#ifndef CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
#define CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS 0
#endif
/** @def CC_ENABLE_PROFILERS
If enabled, will activate various profilers within cocos2d. This statistical data will be output to the console
once per second showing average time (in milliseconds) required to execute the specific routine(s).
Useful for debugging purposes only. It is recommended to leave it disabled.
To enable set it to a value different than 0. Disabled by default.
* If enabled, will activate various profilers within cocos2d. This statistical data will be output to the console
* once per second showing average time (in milliseconds) required to execute the specific routine(s).
* Useful for debugging purposes only. It is recommended to leave it disabled.
* To enable set it to a value different than 0. Disabled by default.
*/
#ifndef CC_ENABLE_PROFILERS
#define CC_ENABLE_PROFILERS 0
#endif
/** Enable Lua engine debug log */
/** Enable Lua engine debug log. */
#ifndef CC_LUA_ENGINE_DEBUG
#define CC_LUA_ENGINE_DEBUG 0
#endif
/** Use physics integration API */
/** Use physics integration API. */
#ifndef CC_USE_PHYSICS
#define CC_USE_PHYSICS 1
#endif
/** Use culling or not */
/** Use culling or not. */
#ifndef CC_USE_CULLING
#define CC_USE_CULLING 1
#endif
@ -294,54 +277,53 @@ To enable set it to a value different than 0. Disabled by default.
#endif
#endif // CC_USE_WEBP
/** Enable Script binding */
/** Enable Script binding. */
#ifndef CC_ENABLE_SCRIPT_BINDING
#define CC_ENABLE_SCRIPT_BINDING 1
#endif
/** @def CC_CONSTRUCTOR_ACCESS
Indicate the init functions access modifier. If value equals to protected, then these functions are protected.
If value equals to public, these functions are public
protected by default.
* Indicate the init functions access modifier. If value equals to protected, then these functions are protected.
* If value equals to public, these functions are public
* protected by default.
*/
#ifndef CC_CONSTRUCTOR_ACCESS
#define CC_CONSTRUCTOR_ACCESS protected
#endif
/** @def CC_ENABLE_ALLOCATOR
Turn on creation of global allocator and pool allocators
as specified by CC_ALLOCATOR_GLOBAL below.
* Turn on creation of global allocator and pool allocators
* as specified by CC_ALLOCATOR_GLOBAL below.
*/
#ifndef CC_ENABLE_ALLOCATOR
# define CC_ENABLE_ALLOCATOR 0
#endif
/** @def CC_ENABLE_ALLOCATOR_DIAGNOSTICS
Turn on debugging of allocators. This is slower, uses
more memory, and should not be used for production builds.
* Turn on debugging of allocators. This is slower, uses
* more memory, and should not be used for production builds.
*/
#ifndef CC_ENABLE_ALLOCATOR_DIAGNOSTICS
# define CC_ENABLE_ALLOCATOR_DIAGNOSTICS CC_ENABLE_ALLOCATOR
#endif
/** @def CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE
Turn on override of global new and delete
as specified by CC_ALLOCATOR_GLOBAL_NEW_DELETE below.
* Turn on override of global new and delete
* as specified by CC_ALLOCATOR_GLOBAL_NEW_DELETE below.
*/
#ifndef CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE
# define CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE 0
# endif//CC_ENABLE_ALLOCATOR_GLOBAL_NEW_DELETE
/** @def CC_ALLOCATOR_GLOBAL
Specify allocator to use for global allocator
* Specify allocator to use for global allocator.
*/
#ifndef CC_ALLOCATOR_GLOBAL
# define CC_ALLOCATOR_GLOBAL cocos2d::allocator::AllocatorStrategyDefault
#endif
/** @def CC_ALLOCATOR_GLOBAL_NEW_DELETE
Specify allocator to use when overriding of new and delete
* Specify allocator to use when overriding of new and delete.
*/
#ifndef CC_ALLOCATOR_GLOBAL_NEW_DELETE
# define CC_ALLOCATOR_GLOBAL_NEW_DELETE cocos2d::allocator::AllocatorStrategyGlobalSmallBlock

View File

@ -1,39 +0,0 @@
/**@defgroup two_d 2D
**/
/**@defgroup three_d 3D
**/
/**@defgroup audio Audio
**/
/**@defgroup base Base
**/
/**@defgroup deprecated Deprecated
**/
/**@defgroup math Math
**/
/**@defgroup network Network
**/
/**@defgroup physics Physics
**/
/**@defgroup platform Platform
**/
/**@defgroup renderer Renderer
**/
/**@defgroup scripting Script Binding
**/
/**@defgroup storage Storage
**/
/**@defgroup ui UI
**/

View File

@ -1359,7 +1359,22 @@ Offset<ProjectNodeOptions> FlatBuffersSerialize::createProjectNodeOptionsForSimu
auto nodeOptions = *(Offset<WidgetOptions>*)(&temp);
std::string filename = "";
float innerspeed = 1.0f;
const tinyxml2::XMLAttribute* objattri = objectData->FirstAttribute();
// inneraction speed
while (objattri)
{
std::string name = objattri->Name();
std::string value = objattri->Value();
if (name == "InnerActionSpeed")
{
innerspeed = atof(objattri->Value());
break;
}
objattri = objattri->Next();
}
// FileData
const tinyxml2::XMLElement* child = objectData->FirstChildElement();
while (child)
@ -1389,7 +1404,8 @@ Offset<ProjectNodeOptions> FlatBuffersSerialize::createProjectNodeOptionsForSimu
return CreateProjectNodeOptions(*_builder,
nodeOptions,
_builder->CreateString(filename));
_builder->CreateString(filename),
innerspeed);
}
}

View File

@ -116,24 +116,46 @@ void ArmatureNodeReader::setPropsWithFlatBuffers(cocos2d::Node *node,
{
auto* custom = static_cast<Armature*>(node);
auto options = (flatbuffers::CSArmatureNodeOption*)nodeOptions;
auto options = (flatbuffers::CSArmatureNodeOption*)nodeOptions;
bool fileExist = false;
std::string errorFilePath = "";
std::string filepath(options->fileData()->path()->c_str());
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(filepath);
std::string filepath(options->fileData()->path()->c_str());
std::string dirpath = fullpath.substr(0, fullpath.find_last_of("/"));
FileUtils::getInstance()->addSearchPath(dirpath);
ArmatureDataManager::getInstance()->addArmatureFileInfo(fullpath);
custom->init(getArmatureName(filepath));
std::string currentname = options->currentAnimationName()->c_str();
if (options->isAutoPlay())
custom->getAnimation()->play(currentname, -1, options->isLoop());
else
if (FileUtils::getInstance()->isFileExist(filepath))
{
custom->getAnimation()->play(currentname);
custom->getAnimation()->gotoAndPause(0);
fileExist = true;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(filepath);
std::string dirpath = fullpath.substr(0, fullpath.find_last_of("/"));
FileUtils::getInstance()->addSearchPath(dirpath);
ArmatureDataManager::getInstance()->addArmatureFileInfo(fullpath);
custom->init(getArmatureName(filepath));
std::string currentname = options->currentAnimationName()->c_str();
if (options->isAutoPlay())
custom->getAnimation()->play(currentname, -1, options->isLoop());
else
{
custom->getAnimation()->play(currentname);
custom->getAnimation()->gotoAndPause(0);
}
}
else
{
errorFilePath = filepath;
fileExist = false;
}
if (!fileExist)
{
auto label = Label::create();
label->setString(__String::createWithFormat("%s missed", filepath.c_str())->getCString());
custom->addChild(label);
}
}
cocos2d::Node* ArmatureNodeReader::createNodeWithFlatBuffers(const flatbuffers::Table *nodeOptions)

View File

@ -26,7 +26,7 @@
#import <Foundation/Foundation.h>
#import <Security/Security.h>
/// @cond
@interface HttpAsynConnection : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
{
}
@ -46,6 +46,7 @@
@property (readonly) NSString *statusString;
@property (strong) NSError *responseError;
@property (strong) NSError *connError;
@property (strong) NSURLConnection *conn;
@ -57,5 +58,5 @@
-(void) startRequest:(NSURLRequest*)request;
@end
/// @endcond
#endif //__HTTPASYNCONNECTION_H__

View File

@ -40,6 +40,7 @@
@synthesize responseCode;
@synthesize statusString;
@synthesize responseError;
@synthesize connError;
@synthesize conn;
@synthesize finish;
@synthesize runLoop;
@ -65,7 +66,9 @@
self.responseData = [NSMutableData data];
getDataTime = 0;
self.responseError = nil;
self.connError = nil;
// create the connection with the target request and this class as the delegate
self.conn = [[[NSURLConnection alloc] initWithRequest:request
@ -109,10 +112,9 @@
*/
if (responseCode < 200 || responseCode >= 300)
{// something went wrong, abort the whole thing
[connection cancel];
finish = true;
return;
self.responseError = [NSError errorWithDomain:@"CCBackendDomain"
code:responseCode
userInfo:@{NSLocalizedDescriptionKey: @"Bad HTTP Response Code"}];
}
[responseData setLength:0];
@ -138,7 +140,7 @@
didFailWithError:(NSError *)error
{
//NSLog(@"Load failed with error %@", [error localizedDescription]);
self.responseError = error;
self.connError = error;
finish = true;
}

View File

@ -242,11 +242,18 @@ static int processTask(HttpRequest *request, NSString* requestType, void *stream
}
//if http connection return error
if (httpAsynConn.connError != nil)
{
NSString* errorString = [httpAsynConn.connError localizedDescription];
strcpy(errorBuffer, [errorString UTF8String]);
return 0;
}
//if http response got error, just log the error
if (httpAsynConn.responseError != nil)
{
NSString* errorString = [httpAsynConn.responseError localizedDescription];
strcpy(errorBuffer, [errorString UTF8String]);
return 0;
}
*responseCode = httpAsynConn.responseCode;

View File

@ -29,7 +29,6 @@
#include "network/HttpRequest.h"
#include "network/HttpResponse.h"
#include "network/HttpClient.h"
NS_CC_BEGIN
@ -41,30 +40,44 @@ namespace network {
*/
/** @brief Singleton that handles asynchrounous http requests
* Once the request completed, a callback will issued in main thread when it provided during make request
/** Singleton that handles asynchrounous http requests.
*
* Once the request completed, a callback will issued in main thread when it provided during make request.
*
* @lua NA
*/
class CC_DLL HttpClient
{
public:
/** Return the shared instance **/
/**
* Get instance of HttpClient.
*
* @return the instance of HttpClient.
*/
static HttpClient *getInstance();
/** Relase the shared instance **/
/**
* Relase the instance of HttpClient.
*/
static void destroyInstance();
/** Enable cookie support. **/
/**
* Enable cookie support.
*
* @param cookieFile the filepath of cookie file.
*/
void enableCookies(const char* cookieFile);
/**
* Set root certificate path for SSL verification.
* @param caFile a full path of root certificate.
* if it is empty, SSL verification is disabled.
*
* @param caFile a full path of root certificate.if it is empty, SSL verification is disabled.
*/
void setSSLVerification(const std::string& caFile);
/**
* Add a get request to task queue
*
* @param request a HttpRequest object, which includes url, response callback etc.
please make sure request->_requestData is clear before calling "send" here.
*/
@ -72,6 +85,7 @@ public:
/**
* Immediate send a request
*
* @param request a HttpRequest object, which includes url, response callback etc.
please make sure request->_requestData is clear before calling "sendImmediate" here.
*/
@ -79,28 +93,32 @@ public:
/**
* Change the connect timeout
* @param value The desired timeout.
* Set the timeout value for connecting.
*
* @param value the timeout value for connecting.
*/
inline void setTimeoutForConnect(int value) {_timeoutForConnect = value;};
/**
* Get connect timeout
* @return int
* Get the timeout value for connecting.
*
* @return int the timeout value for connecting.
*/
inline int getTimeoutForConnect() {return _timeoutForConnect;}
/**
* Change the download timeout
* @param value
* Set the timeout value for reading.
*
* @param value the timeout value for reading.
*/
inline void setTimeoutForRead(int value) {_timeoutForRead = value;};
/**
* Get download timeout
* @return int
* Get the timeout value for reading.
*
* @return int the timeout value for reading.
*/
inline int getTimeoutForRead() {return _timeoutForRead;};

View File

@ -43,9 +43,11 @@ typedef void (cocos2d::Ref::*SEL_HttpResponse)(HttpClient* client, HttpResponse*
#define httpresponse_selector(_SELECTOR) (cocos2d::network::SEL_HttpResponse)(&_SELECTOR)
/**
@brief defines the object which users must packed for HttpClient::send(HttpRequest*) method.
Please refer to tests/test-cpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample
@since v2.0.2
* Defines the object which users must packed for HttpClient::send(HttpRequest*) method.
* Please refer to tests/test-cpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample
* @since v2.0.2
*
* @lua NA
*/
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
@ -57,7 +59,9 @@ typedef void (cocos2d::Ref::*SEL_HttpResponse)(HttpClient* client, HttpResponse*
class CC_DLL HttpRequest : public Ref
{
public:
/** Use this enum type as param in setReqeustType(param) */
/**
* The HttpRequest type enum used in the HttpRequest::setRequestType.
*/
enum class Type
{
GET,
@ -67,11 +71,12 @@ public:
UNKNOWN,
};
/** Constructor
Because HttpRequest object will be used between UI thead and network thread,
requestObj->autorelease() is forbidden to avoid crashes in AutoreleasePool
new/retain/release still works, which means you need to release it manually
Please refer to HttpRequestTest.cpp to find its usage
/**
* Constructor.
* Because HttpRequest object will be used between UI thead and network thread,
requestObj->autorelease() is forbidden to avoid crashes in AutoreleasePool
new/retain/release still works, which means you need to release it manually
Please refer to HttpRequestTest.cpp to find its usage.
*/
HttpRequest()
{
@ -85,7 +90,7 @@ public:
_pUserData = nullptr;
};
/** Destructor */
/** Destructor. */
virtual ~HttpRequest()
{
if (_pTarget)
@ -94,7 +99,12 @@ public:
}
};
/** Override autorelease method to avoid developers to call it */
/**
* Override autorelease method to avoid developers to call it.
* If this function was called, it would trigger assert in debug mode
*
* @return Ref* always return nullptr.
*/
Ref* autorelease(void)
{
CCASSERT(false, "HttpResponse is used between network thread and ui thread \
@ -104,38 +114,60 @@ public:
// setter/getters for properties
/** Required field for HttpRequest object before being sent.
kHttpGet & kHttpPost is currently supported
/**
* Set request type of HttpRequest object before being sent,now it support the enum value of HttpRequest::Type.
*
* @param type the request type.
*/
inline void setRequestType(Type type)
{
_requestType = type;
};
/** Get back the kHttpGet/Post/... enum value */
/**
* Get the request type of HttpRequest object.
*
* @return HttpRequest::Type.
*/
inline Type getRequestType()
{
return _requestType;
};
/** Required field for HttpRequest object before being sent.
/**
* Set the url address of HttpRequest object.
* The url value could be like these: "http://httpbin.org/ip" or "https://httpbin.org/get"
*
* @param url the string pointer.
*/
inline void setUrl(const char* url)
{
_url = url;
};
/** Get back the setted url */
/**
* Get the url address of HttpRequest object.
*
* @return const char* the pointer of _url.
*/
inline const char* getUrl()
{
return _url.c_str();
};
/** Option field. You can set your post data here
/**
* Set the request data of HttpRequest object.
*
* @param buffer the buffer of request data, it support binary data.
* @param len the size of request data.
*/
inline void setRequestData(const char* buffer, size_t len)
{
_requestData.assign(buffer, buffer + len);
};
/** Get the request data pointer back */
/**
* Get the request data pointer of HttpRequest object.
*
* @return char* the request data pointer.
*/
inline char* getRequestData()
{
if(_requestData.size() != 0)
@ -143,48 +175,78 @@ public:
return nullptr;
}
/** Get the size of request data back */
/**
* Get the size of request data
*
* @return ssize_t the size of request data
*/
inline ssize_t getRequestDataSize()
{
return _requestData.size();
}
/** Option field. You can set a string tag to identify your request, this tag can be found in HttpResponse->getHttpRequest->getTag()
/**
* Set a string tag to identify your request.
* This tag can be found in HttpResponse->getHttpRequest->getTag().
*
* @param tag the string pointer
*/
inline void setTag(const char* tag)
{
_tag = tag;
};
/** Get the string tag back to identify the request.
The best practice is to use it in your MyClass::onMyHttpRequestCompleted(sender, HttpResponse*) callback
/**
* Get the string tag to identify the request.
* The best practice is to use it in your MyClass::onMyHttpRequestCompleted(sender, HttpResponse*) callback.
*
* @return const char* the pointer of _tag
*/
inline const char* getTag()
{
return _tag.c_str();
};
/** Option field. You can attach a customed data in each request, and get it back in response callback.
But you need to new/delete the data pointer manully
/**
* Set user-customed data of HttpRequest object.
* You can attach a customed data in each request, and get it back in response callback.
* But you need to new/delete the data pointer manully.
*
* @param pUserData the string pointer
*/
inline void setUserData(void* pUserData)
{
_pUserData = pUserData;
};
/** Get the pre-setted custom data pointer back.
Don't forget to delete it. HttpClient/HttpResponse/HttpRequest will do nothing with this pointer
/**
* Get the user-customed data pointer which were pre-setted.
* Don't forget to delete it. HttpClient/HttpResponse/HttpRequest will do nothing with this pointer.
*
* @return void* the pointer of user-customed data.
*/
inline void* getUserData()
{
return _pUserData;
};
/** Required field. You should set the callback selector function at ack the http request completed
/**
* Set the target and related callback selector.
* When response come back, it would call (pTarget->*pSelector) to process something.
*
* @param pTarget the target object pointer.
* @param pSelector the callback function.
*/
CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(Ref* pTarget, SEL_CallFuncND pSelector)
{
setResponseCallback(pTarget, (SEL_HttpResponse) pSelector);
}
/**
* Set the target and related callback selector of HttpRequest object.
* When response come back, we would call (pTarget->*pSelector) to process response data.
*
* @param pTarget the target object pointer.
* @param pSelector the SEL_HttpResponse function.
*/
CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(Ref* pTarget, SEL_HttpResponse pSelector)
{
_pTarget = pTarget;
@ -195,49 +257,81 @@ public:
_pTarget->retain();
}
}
/**
* Set response callback function of HttpRequest object.
* When response come back, we would call _pCallback to process response data.
*
* @param callback the ccHttpRequestCallback function.
*/
inline void setResponseCallback(const ccHttpRequestCallback& callback)
{
_pCallback = callback;
}
/** Get the target of callback selector funtion, mainly used by HttpClient */
/**
* Get the target of callback selector funtion, mainly used by HttpClient.
*
* @return Ref* the target of callback selector funtion
*/
inline Ref* getTarget()
{
return _pTarget;
}
/* This sub class is just for migration SEL_CallFuncND to SEL_HttpResponse,
someday this way will be removed */
/**
* This sub class is just for migration SEL_CallFuncND to SEL_HttpResponse,someday this way will be removed.
*
* @lua NA
*/
class _prxy
{
public:
/** Constructor. */
_prxy( SEL_HttpResponse cb ) :_cb(cb) {}
/** Destructor. */
~_prxy(){};
/** Destructor. */
operator SEL_HttpResponse() const { return _cb; }
CC_DEPRECATED_ATTRIBUTE operator SEL_CallFuncND() const { return (SEL_CallFuncND) _cb; }
protected:
SEL_HttpResponse _cb;
};
/** Get the selector function pointer, mainly used by HttpClient */
/**
* Get _prxy object by the _pSelector.
*
* @return _prxy the _prxy object
*/
inline _prxy getSelector()
{
return _prxy(_pSelector);
}
/**
* Get ccHttpRequestCallback callback function.
*
* @return const ccHttpRequestCallback& ccHttpRequestCallback callback function.
*/
inline const ccHttpRequestCallback& getCallback()
{
return _pCallback;
}
/** Set any custom headers **/
/**
* Set custom-defined headers.
*
* @param pHeaders the string vector of custom-defined headers.
*/
inline void setHeaders(std::vector<std::string> pHeaders)
{
_headers=pHeaders;
}
/** Get custom headers **/
/**
* Get custom headers.
*
* @return std::vector<std::string> the string vector of custom-defined headers.
*/
inline std::vector<std::string> getHeaders()
{
return _headers;

View File

@ -33,15 +33,17 @@ NS_CC_BEGIN
namespace network {
/**
@brief defines the object which users will receive at onHttpCompleted(sender, HttpResponse) callback
Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample
@since v2.0.2
* @brief defines the object which users will receive at onHttpCompleted(sender, HttpResponse) callback.
* Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample.
* @since v2.0.2.
* @lua NA
*/
class CC_DLL HttpResponse : public cocos2d::Ref
{
public:
/** Constructor, it's used by HttpClient internal, users don't need to create HttpResponse manually
@param request the corresponding HttpRequest which leads to this response
/**
* Constructor, it's used by HttpClient internal, users don't need to create HttpResponse manually.
* @param request the corresponding HttpRequest which leads to this response.
*/
HttpResponse(HttpRequest* request)
{
@ -57,8 +59,9 @@ public:
_responseDataString = "";
}
/** Destructor, it will be called in HttpClient internal,
users don't need to desturct HttpResponse object manully
/**
* Destructor, it will be called in HttpClient internal.
* Users don't need to desturct HttpResponse object manully.
*/
virtual ~HttpResponse()
{
@ -68,7 +71,11 @@ public:
}
}
/** Override autorelease method to prevent developers from calling it */
/**
* Override autorelease method to prevent developers from calling it.
* If this method is called , it would trigger CCASSERT.
* @return cocos2d::Ref* always return nullptr.
*/
cocos2d::Ref* autorelease(void)
{
CCASSERT(false, "HttpResponse is used between network thread and ui thread \
@ -78,44 +85,59 @@ public:
// getters, will be called by users
/** Get the corresponding HttpRequest object which leads to this response
There's no paired setter for it, coz it's already setted in class constructor
/**
* Get the corresponding HttpRequest object which leads to this response.
* There's no paired setter for it, because it's already setted in class constructor
* @return HttpRequest* the corresponding HttpRequest object which leads to this response.
*/
inline HttpRequest* getHttpRequest()
{
return _pHttpRequest;
}
/** To see if the http reqeust is returned successfully,
Althrough users can judge if (http return code = 200), we want an easier way
If this getter returns false, you can call getResponseCode and getErrorBuffer to find more details
/**
* To see if the http reqeust is returned successfully.
* Althrough users can judge if (http response code = 200), we want an easier way.
* If this getter returns false, you can call getResponseCode and getErrorBuffer to find more details.
* @return bool the flag that represent whether the http request return sucesssfully or not.
*/
inline bool isSucceed()
{
return _succeed;
};
/** Get the http response raw data */
/**
* Get the http response data.
* @return std::vector<char>* the pointer that point to the _responseData.
*/
inline std::vector<char>* getResponseData()
{
return &_responseData;
}
/** get the Rawheader **/
/**
* Get the response headers.
* @return std::vector<char>* the pointer that point to the _responseHeader.
*/
inline std::vector<char>* getResponseHeader()
{
return &_responseHeader;
}
/** Get the http response errorCode
* I know that you want to see http 200 :)
/**
* Get the http response code to judge whether response is sucessful or not.
* I know that you want to see the _responseCode is 200.
* If _responseCode is not 200, you should check the meaning for _responseCode by the net.
* @return long the value of _responseCode
*/
inline long getResponseCode()
{
return _responseCode;
}
/** Get the rror buffer which will tell you more about the reason why http request failed
/**
* Get the rror buffer which will tell you more about the reason why http request failed.
* @return const char* the pointer that point to _errorBuffer.
*/
inline const char* getErrorBuffer()
{
@ -126,9 +148,10 @@ public:
// users should avoid invoking these methods
/** Set if the http request is returned successfully,
Althrough users can judge if (http code == 200), we want a easier way
This setter is mainly used in HttpClient, users mustn't set it directly
/**
* Set whether the http request is returned successfully or not,
* This setter is mainly used in HttpClient, users mustn't set it directly
* @param value the flag represent whether the http request is successful or not.
*/
inline void setSucceed(bool value)
{
@ -136,14 +159,18 @@ public:
};
/** Set the http response raw buffer, is used by HttpClient
/**
* Set the http response data buffer, it is used by HttpClient.
* @param data the pointer point to the response data buffer.
*/
inline void setResponseData(std::vector<char>* data)
{
_responseData = *data;
}
/** Set the http response Header raw buffer, is used by HttpClient
/**
* Set the http response headers buffer, it is used by HttpClient.
* @param data the pointer point to the response headers buffer.
*/
inline void setResponseHeader(std::vector<char>* data)
{
@ -151,7 +178,9 @@ public:
}
/** Set the http response errorCode
/**
* Set the http response code.
* @param value the http response code that represent whether the request is successful or not.
*/
inline void setResponseCode(long value)
{
@ -159,7 +188,9 @@ public:
}
/** Set the error buffer which will tell you more the reason why http request failed
/**
* Set the error buffer which will tell you more the reason why http request failed.
* @param value a string pointer that point to the reason.
*/
inline void setErrorBuffer(const char* value)
{
@ -167,12 +198,21 @@ public:
_errorBuffer.assign(value);
};
/**
* Set the response data by the string pointer and the defined size.
* @param value a string pointer that point to response data buffer.
* @param n the defined size that the response data buffer would be copied.
*/
inline void setResponseDataString(const char* value, size_t n)
{
_responseDataString.clear();
_responseDataString.assign(value, n);
}
/**
* Get the string pointer that point to the response data.
* @return const char* the string pointer that point to the response data.
*/
inline const char* getResponseDataString()
{
return _responseDataString.c_str();

View File

@ -73,36 +73,88 @@ class SIOClientImpl;
class SIOClient;
/**
* @brief Singleton and wrapper class to provide static creation method as well as registry of all sockets
* Singleton and wrapper class to provide static creation method as well as registry of all sockets.
*
* @lua NA
*/
class CC_DLL SocketIO
{
public:
/**
* Get instance of SocketIO.
*
* @return SocketIO* the instance of SocketIO.
*/
static SocketIO* getInstance();
static void destroyInstance();
/**
* @brief The delegate class to process socket.io events
* The delegate class to process socket.io events.
* @lua NA
*/
class SIODelegate
{
public:
/** Destructor of SIODelegate. */
virtual ~SIODelegate() {}
/**
* Pure virtual callback function, this function should be overrided by the subclass.
*
* This function would be called when the related SIOClient object recevie messages that mean it have connected to endpoint sucessfully.
*
* @param client the connected SIOClient object.
*/
virtual void onConnect(SIOClient* client) = 0;
/**
* Pure virtual callback function, this function should be overrided by the subclass.
*
* This function would be called wwhen the related SIOClient object recevie message or json message.
*
* @param client the connected SIOClient object.
* @param data the message,it could be json message
*/
virtual void onMessage(SIOClient* client, const std::string& data) = 0;
/**
* Pure virtual callback function, this function should be overrided by the subclass.
*
* This function would be called when the related SIOClient object disconnect or recevie disconnect signal.
*
* @param client the connected SIOClient object.
*/
virtual void onClose(SIOClient* client) = 0;
/**
* Pure virtual callback function, this function should be overrided by the subclass.
*
* This function would be called wwhen the related SIOClient object recevie error signal or didn't connect the endpoint but do some network operation,eg.,send and emit,etc.
*
* @param client the connected SIOClient object.
* @param data the error message
*/
virtual void onError(SIOClient* client, const std::string& data) = 0;
/**
* Fire event to script when the related SIOClient object receive the fire event signal.
*
* @param client the connected SIOClient object.
* @param eventName the event's name.
* @param data the event's data information.
*/
virtual void fireEventToScript(SIOClient* client, const std::string& eventName, const std::string& data) { CCLOG("SIODelegate event '%s' fired with data: %s", eventName.c_str(), data.c_str()); };
};
/**
* @brief Static client creation method, similar to socketio.connect(uri) in JS
* @param delegate The delegate which want to receive events from the socket.io client
* @param uri The URI of the socket.io server
* @return An initialized SIOClient if connected successfully, otherwise NULL
* Static client creation method, similar to socketio.connect(uri) in JS.
* @param uri the URI of the socket.io server.
* @param delegate the delegate which want to receive events from the socket.io client.
* @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
*/
static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate);
/**
* Static client creation method, similar to socketio.connect(uri) in JS.
* @param delegate the delegate which want to receive events from the socket.io client.
* @param uri the URI of the socket.io server.
* @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
*/
CC_DEPRECATED_ATTRIBUTE static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri);
private:
@ -129,8 +181,10 @@ typedef std::function<void(SIOClient*, const std::string&)> SIOEvent;
typedef std::unordered_map<std::string, SIOEvent> EventRegistry;
/**
* @brief A single connection to a socket.io endpoint
*/
* A single connection to a socket.io endpoint.
*
* @lua NA
*/
class CC_DLL SIOClient
: public cocos2d::Ref
{
@ -153,37 +207,64 @@ private:
friend class SIOClientImpl;
public:
/**
* Construtor of SIOClient class.
*
* @param host the string that represent the host address.
* @param port the int value represent the port number.
* @param path the string that represent endpoint.
* @param impl the SIOClientImpl object.
* @param delegate the SIODelegate object.
*/
SIOClient(const std::string& host, int port, const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate);
/**
* Destructior of SIOClient class.
*/
virtual ~SIOClient(void);
/**
* @brief Returns the delegate for the client
* Get the delegate for the client
* @return the delegate object for the client
*/
SocketIO::SIODelegate* getDelegate() { return _delegate; };
/**
* @brief Disconnect from the endpoint, onClose will be called on the delegate when complete
* Disconnect from the endpoint, onClose will be called for the delegate when complete
*/
void disconnect();
/**
* @brief Send a message to the socket.io server
* Send a message to the socket.io server.
*
* @param s message.
*/
void send(std::string s);
/**
* @brief The delegate class to process socket.io events
* Emit the eventname and the args to the endpoint that _path point to.
* @param eventname
* @param args
*/
void emit(std::string eventname, std::string args);
/**
* @brief Used to register a socket.io event callback
* Event argument should be passed using CC_CALLBACK2(&Base::function, this)
* Used to register a socket.io event callback.
* Event argument should be passed using CC_CALLBACK2(&Base::function, this).
* @param eventName.
* @param e the callback function.
*/
void on(const std::string& eventName, SIOEvent e);
/**
* Set tag of SIOClient.
* The tag is used to distinguish the various SIOClient objects.
* @param tag string object.
*/
inline void setTag(const char* tag)
{
_tag = tag;
};
/**
* Get tag of SIOClient.
* @return const char* the pointer point to the _tag.
*/
inline const char* getTag()
{
return _tag.c_str();

View File

@ -51,17 +51,21 @@ class CC_DLL WebSocket
{
public:
/**
* Construtor of WebSocket.
*
* @js ctor
*/
WebSocket();
/**
* Destructor of WebSocket.
*
* @js NA
* @lua NA
*/
virtual ~WebSocket();
/**
* @brief Data structure for message
* Data structure for message
*/
struct Data
{
@ -72,36 +76,67 @@ public:
};
/**
* @brief Errors in websocket
* ErrorCode enum used to represent the error in the websocket.
*/
enum class ErrorCode
{
TIME_OUT,
CONNECTION_FAILURE,
UNKNOWN,
TIME_OUT, /** &lt; value 0 */
CONNECTION_FAILURE, /** &lt; value 1 */
UNKNOWN, /** &lt; value 2 */
};
/**
* Websocket state
* State enum used to represent the Websocket state.
*/
enum class State
{
CONNECTING,
OPEN,
CLOSING,
CLOSED,
CONNECTING, /** &lt; value 0 */
OPEN, /** &lt; value 1 */
CLOSING, /** &lt; value 2 */
CLOSED, /** &lt; value 3 */
};
/**
* @brief The delegate class to process websocket events.
* The delegate class is used to process websocket events.
*
* The most member function are pure virtual functions,they should be implemented the in subclass.
* @lua NA
*/
class Delegate
{
public:
/** Destructor of Delegate. */
virtual ~Delegate() {}
/**
* This function to be called after the client connection complete a handshake with the remote server.
* This means that the WebSocket connection is ready to send and receive data.
*
* @param ws The WebSocket object connected
*/
virtual void onOpen(WebSocket* ws) = 0;
/**
* This function to be called when data has appeared from the server for the client connection.
*
* @param ws The WebSocket object connected.
* @param data Data object for message.
*/
virtual void onMessage(WebSocket* ws, const Data& data) = 0;
/**
* When the WebSocket object connected wants to close or the protocol won't get used at all and current _readyState is State::CLOSING,this function is to be called.
*
* @param ws The WebSocket object connected.
*/
virtual void onClose(WebSocket* ws) = 0;
/**
* This function is to be called in the following cases:
* 1. client connection is failed.
* 2. the request client connection has been unable to complete a handshake with the remote server.
* 3. the protocol won't get used at all after this callback and current _readyState is State::CONNECTING.
* 4. when a socket descriptor needs to be removed from an external polling array. in is again the struct libwebsocket_pollargs containing the fd member to be removed. If you are using the internal polling loop, you can just ignore it and current _readyState is State::CONNECTING.
*
* @param ws The WebSocket object connected.
* @param error WebSocket::ErrorCode enum,would be ErrorCode::TIME_OUT or ErrorCode::CONNECTION_FAILURE.
*/
virtual void onError(WebSocket* ws, const ErrorCode& error) = 0;
};
@ -111,7 +146,8 @@ public:
* It needs to be invoked right after websocket instance is allocated.
* @param delegate The delegate which want to receive event from websocket.
* @param url The URL of websocket server.
* @return true: Success, false: Failure
* @return true: Success, false: Failure.
* @lua NA
*/
bool init(const Delegate& delegate,
const std::string& url,
@ -119,11 +155,18 @@ public:
/**
* @brief Sends string data to websocket server.
*
* @param message string data.
* @lua sendstring
*/
void send(const std::string& message);
/**
* @brief Sends binary data to websocket server.
*
* @param binaryMsg binary string data.
* @param len the size of binary string data.
* @lua sendstring
*/
void send(const unsigned char* binaryMsg, unsigned int len);
@ -134,6 +177,7 @@ public:
/**
* @brief Gets current state of connection.
* @return State the state value coule be State::CONNECTING, State::OPEN, State::CLOSING or State::CLOSED
*/
State getReadyState();

View File

@ -47,99 +47,250 @@ typedef Vec2 Vect;
const PhysicsMaterial PHYSICSBODY_MATERIAL_DEFAULT(0.1f, 0.5f, 0.5f);
/**
* @addtogroup physics
* @{
*/
/**
* 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 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().
*
* 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 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 CC_DLL PhysicsBody : public Ref
{
public:
/** create a body with defult mass and moment. */
/**
Create a body with default mass and moment.
This default mass value is 1.0.
This default moment value is 200.
@return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* create();
/** create a body with mass and defult moment. */
/**
Create a body with mass and default moment.
@param mass This body's mass.
@return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* create(float mass);
/** create a body with mass and moment. */
/**
Create a body with mass and moment.
@param mass This body's mass.
@param moment This body's moment.
@return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* create(float mass, float moment);
/** Create a body contains a circle shape. */
/**
Create a body contains a circle.
@param radius A float number, it is the circle's radius.
@param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
@param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
@return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createCircle(float radius, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/** Create a body contains a box shape. */
/**
* Create a body contains a box shape.
*
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/**
* @brief Create a body contains a polygon shape.
* points is an array of Vec2 structs defining a convex hull with a clockwise winding.
*
* @param points Points is an array of Vec2 structs defining a convex hull with a clockwise winding.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createPolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/** Create a body contains a EdgeSegment shape. */
/**
Create a body contains a EdgeSegment shape.
* @param a It's the edge's begin position.
* @param b It's the edge's end position.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createEdgeSegment(const Vec2& a, const Vec2& b, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/** Create a body contains a EdgeBox shape. */
/**
Create a body contains a EdgeBox shape.
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createEdgeBox(const Size& size, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1, const Vec2& offset = Vec2::ZERO);
/** Create a body contains a EdgePolygon shape. */
/**
Create a body contains a EdgePolygon shape.
* @param points Points is an array of Vec2 structs defining a convex hull with a clockwise winding.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createEdgePolygon(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/** Create a body contains a EdgeChain shape. */
/**
Create a body contains a EdgeChain shape.
* @param points A Vec2 object pointer, it contains an array of points.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsBody object pointer.
*/
static PhysicsBody* createEdgeChain(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSBODY_MATERIAL_DEFAULT, float border = 1);
/*
* @brief add a shape to body
* @param shape the shape to be added
* @param addMassAndMoment if this is true, the shape's mass and moment will be added to body. the default is true
/**
* @brief Add a shape to body.
* @param shape The shape to be added.
* @param addMassAndMoment If this is true, the shape's mass and moment will be added to body. The default is true.
* @return This shape's pointer if added success or nullptr if failed.
*/
virtual PhysicsShape* addShape(PhysicsShape* shape, bool addMassAndMoment = true);
/*
* @brief remove a shape from body
* @param shape the shape to be removed
* @param reduceMassAndMoment if this is true, the body mass and moment will be reduced by shape. the default is true
/**
* @brief Remove a shape from body.
* @param shape Shape the shape to be removed.
* @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
*/
void removeShape(PhysicsShape* shape, bool reduceMassAndMoment = true);
/*
* @brief remove a shape from body
* @param tag the tag of the shape to be removed
* @param reduceMassAndMoment if this is true, the body mass and moment will be reduced by shape. the default is true
/**
* @brief Remove a shape from body.
* @param tag The tag of the shape to be removed.
* @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
*/
void removeShape(int tag, bool reduceMassAndMoment = true);
/* remove all shapes */
/**
Remove all shapes.
* @param reduceMassAndMoment If this is true, the body mass and moment will be reduced by shape. The default is true.
*/
void removeAllShapes(bool reduceMassAndMoment = true);
/* get the body shapes. */
/**
Get the body shapes.
* @return A Vector<PhysicsShape*> object contains PhysicsShape pointer.
*/
inline const Vector<PhysicsShape*>& getShapes() const { return _shapes; }
/* get the first shape of the body shapes. */
/**
Get the first shape of the body shapes.
@return The first shape in this body.
*/
inline PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; }
/* get the shape of the body. */
/**
get the shape of the body.
@param tag An interger number that identifies a PhysicsShape object.
@return A PhysicsShape object pointer or nullptr if no shapes were found.
*/
PhysicsShape* getShape(int tag) const;
/** Applies a immediate force to body. */
/**
Applies a continuous force to body.
@param force The force is applies to this body.
*/
virtual void applyForce(const Vect& force);
/** Applies a immediate force to body. */
/**
Applies a continuous force to body.
@param force The force is applies to this body.
@param offset A Vec2 object, it is the offset from the bodys center of gravity in world coordinates.
*/
virtual void applyForce(const Vect& force, const Vec2& offset);
/** reset all the force applied to body. */
/**
reset all the force applied to body.
*/
virtual void resetForces();
/** Applies a continuous force to body. */
/**
Applies a immediate force to body.
@param impulse The impulse is applies to this body.
*/
virtual void applyImpulse(const Vect& impulse);
/** Applies a continuous force to body. */
/**
Applies a immediate force to body.
@param impulse The impulse is applies to this body.
@param offset A Vec2 object, it is the offset from the bodys center of gravity in world coordinates.
*/
virtual void applyImpulse(const Vect& impulse, const Vec2& offset);
/** Applies a torque force to body. */
/**
Applies a torque force to body.
@param torque The torque is applies to this body.
*/
virtual void applyTorque(float torque);
/** set the velocity of a body */
/**
Set the velocity of a body.
@param velocity The velocity is set to this body.
*/
virtual void setVelocity(const Vect& velocity);
/** get the velocity of a body */
/** Get the velocity of a body. */
virtual Vec2 getVelocity();
/** set the angular velocity of a body */
/**
Set the angular velocity of a body.
@param velocity The angular velocity is set to this body.
*/
virtual void setAngularVelocity(float velocity);
/** get the angular velocity of a body at a local point */
/** Get the angular velocity of a body at a local point.*/
virtual Vec2 getVelocityAtLocalPoint(const Vec2& point);
/** get the angular velocity of a body at a world point */
virtual Vec2 getVelocityAtWorldPoint(const Vec2& point);
/** get the angular velocity of a body */
virtual float getAngularVelocity();
/** set the max of velocity */
virtual void setVelocityLimit(float limit);
/** get the max of velocity */
virtual float getVelocityLimit();
/** set the max of angular velocity */
virtual void setAngularVelocityLimit(float limit);
/** get the max of angular velocity */
virtual float getAngularVelocityLimit();
@ -156,73 +307,108 @@ public:
/**
* A mask that defines which categories this physics body belongs to.
*
* Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.
* The default value is 0xFFFFFFFF (all bits set).
* @param bitmask An interger number, the default value is 0xFFFFFFFF (all bits set).
*/
void setCategoryBitmask(int bitmask);
/**
* A mask that defines which categories of bodies cause intersection notifications with this physics body.
*
* When two bodies share the same space, each bodys category mask is tested against the other bodys contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics worlds delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.
* The default value is 0x00000000 (all bits cleared).
* @param bitmask An interger number, the default value is 0x00000000 (all bits cleared).
*/
void setContactTestBitmask(int bitmask);
/**
* A mask that defines which categories of physics bodies can collide with this physics body.
*
* When two physics bodies contact each other, a collision may occur. This bodys collision mask is compared to the other bodys category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a bodys velocity.
* The default value is 0xFFFFFFFF (all bits set).
* @param bitmask An interger number, the default value is 0xFFFFFFFF (all bits set).
*/
void setCollisionBitmask(int bitmask);
/** Return bitmask of first shape, if there is no shape in body, return default value.(0xFFFFFFFF) */
/**
Return bitmask of first shape.
* @return If there is no shape in body, return default value.(0xFFFFFFFF)
*/
int getCategoryBitmask() const;
/** Return bitmask of first shape, if there is no shape in body, return default value.(0x00000000) */
/**
Return bitmask of first shape.
* @return If there is no shape in body, return default value.(0x00000000)
*/
int getContactTestBitmask() const;
/** Return bitmask of first shape, if there is no shape in body, return default value.(0xFFFFFFFF) */
/**
Return bitmask of first shape.
@return If there is no shape in body, return default value.(0xFFFFFFFF)
*/
int getCollisionBitmask() const;
/**
* set the group of body
* Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index)
* it have high priority than bit masks
* Set the group of body.
*
* Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index).
* It have high priority than bit masks.
*/
void setGroup(int group);
/** Return group of first shape, if there is no shape in body, return default value.(0) */
/**
Return group of first shape.
@return If there is no shape in body, return default value.(0)
*/
int getGroup() const;
/** get the body position. */
const Vec2& getPosition();
/** get the body rotation. */
float getRotation();
/** set body position offset, it's the position witch relative to node */
void setPositionOffset(const Vec2& position);
/** get body position offset. */
const Vec2& getPositionOffset() const { return _positionOffset; }
/** set body rotation offset, it's the rotation witch relative to node */
void setRotationOffset(float rotation);
/** set the body rotation offset */
float getRotationOffset() const { return _rotationOffset; }
/**
* @brief test the body is dynamic or not.
* a dynamic body will effect with gravity.
* @brief Test the body is dynamic or not.
*
* A dynamic body will effect with gravity.
*/
inline bool isDynamic() const { return _dynamic; }
/**
* @brief set dynamic to body.
* a dynamic body will effect with gravity.
* @brief Set dynamic to body.
*
* A dynamic body will effect with gravity.
*/
void setDynamic(bool dynamic);
/**
* @brief set the body mass.
* @note if you need add/subtract mass to body, don't use setMass(getMass() +/- mass), because the mass of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMass() instead.
* @brief Set the body mass.
*
* @attension 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. */
/** 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.
* @brief Add mass to body.
*
* @param mass 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)
@ -231,73 +417,92 @@ public:
void addMass(float mass);
/**
* @brief set the body moment of inertia.
* @note if you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead.
* @brief Set the body moment of inertia.
*
* @note If you need add/subtract moment to body, don't use setMoment(getMoment() +/- moment), because the moment of body may be equal to PHYSICS_INFINITY, it will cause some unexpected result, please use addMoment() instead.
*/
void setMoment(float moment);
/** get the body moment of inertia. */
/** Get the body moment of inertia. */
inline float getMoment() const { return _moment; }
/**
* @brief add moment of inertia to body.
* if _moment(moment of the body) == PHYSICS_INFINITY, it remains.
* @brief Add moment of inertia to body.
*
* @param moment If _moment(moment of the body) == PHYSICS_INFINITY, it remains.
* if moment == PHYSICS_INFINITY, _moment will be PHYSICS_INFINITY.
* if moment == -PHYSICS_INFINITY, _moment will not change.
* if moment + _moment <= 0, _moment will equal to MASS_DEFAULT(1.0)
* other wise, moment = moment + _moment;
*/
void addMoment(float moment);
/** get linear damping. */
inline float getLinearDamping() const { return _linearDamping; }
/**
* set linear damping.
* it is used to simulate fluid or air friction forces on the body.
* the value is 0.0f to 1.0f.
* Set linear damping.
*
* it is used to simulate fluid or air friction forces on the body.
* @param damping The value is 0.0f to 1.0f.
*/
inline void setLinearDamping(float damping) { _linearDamping = damping; updateDamping(); }
/** get angular damping. */
/** Get angular damping. */
inline float getAngularDamping() const { return _angularDamping; }
/**
* set angular damping.
* it is used to simulate fluid or air friction forces on the body.
* the value is 0.0f to 1.0f.
* Set angular damping.
*
* It is used to simulate fluid or air friction forces on the body.
* @param damping The value is 0.0f to 1.0f.
*/
inline void setAngularDamping(float damping) { _angularDamping = damping; updateDamping(); }
/** whether the body is at rest */
/** Whether the body is at rest. */
bool isResting() const;
/** set body to rest */
void setResting(bool rest) const;
/**
* whether the body is enabled
* if the body it isn't enabled, it will not has simulation by world
/**
* Whether the body is enabled.
*
* If the body it isn't enabled, it will not has simulation by world.
*/
inline bool isEnabled() const { return _enabled; }
/**
* set the enable value.
* if the body it isn't enabled, it will not has simulation by world
* Set the enable value.
*
* If the body it isn't enabled, it will not has simulation by world.
*/
void setEnable(bool enable);
/** whether the body can rotation */
/** Whether the body can rotation. */
inline bool isRotationEnabled() const { return _rotationEnabled; }
/** set the body is allow rotation or not */
/** Set the body is allow rotation or not */
void setRotationEnable(bool enable);
/** whether this physics body is affected by the physics worlds gravitational force. */
/** Whether this physics body is affected by the physics worlds gravitational force. */
inline bool isGravityEnabled() const { return _gravityEnabled; }
/** set the body is affected by the physics world's gravitational force or not. */
/** Set the body is affected by the physics world's gravitational force or not. */
void setGravityEnable(bool enable);
/** get the body's tag */
/** Get the body's tag. */
inline int getTag() const { return _tag; }
/** set the body's tag */
/** set the body's tag. */
inline void setTag(int tag) { _tag = tag; }
/** convert the world point to local */
/** Convert the world point to local. */
Vec2 world2Local(const Vec2& point);
/** convert the local point to world */
/** Convert the local point to world. */
Vec2 local2World(const Vec2& point);
/** Get the rigid body of chipmunk. */
cpBody* getCPBody() { return _cpBody; }
protected:
@ -354,6 +559,8 @@ protected:
friend class ProtectedNode;
};
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -55,7 +55,14 @@ typedef struct CC_DLL PhysicsContactData
}PhysicsContactData;
/**
* @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated.
* @addtogroup physics
* @{
*/
/**
* @brief Contact infomation.
* It will created automatically when two shape contact with each other. And it will destoried automatically when two shape separated.
*/
class CC_DLL PhysicsContact : public EventCustom
{
@ -70,21 +77,29 @@ public:
SEPERATE
};
/** get contact shape A. */
/** Get contact shape A. */
inline PhysicsShape* getShapeA() const { return _shapeA; }
/** get contact shape B. */
/** Get contact shape B. */
inline PhysicsShape* getShapeB() const { return _shapeB; }
/** get contact data */
/** Get contact data. */
inline const PhysicsContactData* getContactData() const { return _contactData; }
/** get previous contact data */
/** Get previous contact data */
inline const PhysicsContactData* getPreContactData() const { return _preContactData; }
/** get data. */
/** Get data. */
inline void* getData() const { return _data; }
/**
* @brief set data to contact. you must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact seperate.
* @brief Set data to contact.
* You must manage the memory yourself, Generally you can set data at contact begin, and distory it at contact seperate.
*/
inline void setData(void* data) { _data = data; }
/** get the event code */
/** Get the event code */
EventCode getEventCode() const { return _eventCode; };
private:
@ -123,25 +138,25 @@ private:
friend class PhysicsWorld;
};
/*
* @brief presolve value generated when onContactPreSolve called.
/**
* @brief Presolve value generated when onContactPreSolve called.
*/
class CC_DLL PhysicsContactPreSolve
{
public:
/** get restitution between two bodies*/
/** Get restitution between two bodies.*/
float getRestitution() const;
/** get friction between two bodies*/
/** Get friction between two bodies.*/
float getFriction() const;
/** get surface velocity between two bodies*/
/** Get surface velocity between two bodies.*/
Vec2 getSurfaceVelocity() const;
/** set the restitution*/
/** Set the restitution.*/
void setRestitution(float restitution);
/** set the friction*/
/** Set the friction.*/
void setFriction(float friction);
/** set the surface velocity*/
/** Set the surface velocity.*/
void setSurfaceVelocity(const Vect& velocity);
/** ignore the rest of the contact presolve and postsolve callbacks */
/** Ignore the rest of the contact presolve and postsolve callbacks. */
void ignore();
private:
@ -154,17 +169,17 @@ private:
friend class EventListenerPhysicsContact;
};
/*
* @brief postsolve value generated when onContactPostSolve called.
/**
* @brief Postsolve value generated when onContactPostSolve called.
*/
class CC_DLL PhysicsContactPostSolve
{
public:
/** get restitution between two bodies*/
/** Get restitution between two bodies.*/
float getRestitution() const;
/** get friction between two bodies*/
/** Get friction between two bodies.*/
float getFriction() const;
/** get surface velocity between two bodies*/
/** Get surface velocity between two bodies.*/
Vec2 getSurfaceVelocity() const;
private:
@ -177,37 +192,44 @@ private:
friend class EventListenerPhysicsContact;
};
/* contact listener. it will recive all the contact callbacks. */
/** Contact listener. It will recive all the contact callbacks. */
class CC_DLL EventListenerPhysicsContact : public EventListenerCustom
{
public:
/** create the listener */
/** Create the listener. */
static EventListenerPhysicsContact* create();
/** Check the listener is available.
*@return Ture if there's one available callback function at least, false if there's no one.
*/
virtual bool checkAvailable() override;
/** Clone an object from this listener.*/
virtual EventListenerPhysicsContact* clone() override;
protected:
/**
* it will be call when two body have contact.
* if return false, it will not invoke callbacks
* It will be call when two body have contact.
* if return false, it will not invoke callbacks.
*/
virtual bool hitTest(PhysicsShape* shapeA, PhysicsShape* shapeB);
public:
/*
* @brief it will called at two shapes start to contact, and only call it once.
/**
* @brief It will called at two shapes start to contact, and only call it once.
*/
std::function<bool(PhysicsContact& contact)> onContactBegin;
/*
/**
* @brief Two shapes are touching during this step. Return false from the callback to make world ignore the collision this step or true to process it normally. Additionally, you may override collision values, restitution, or surface velocity values.
*/
std::function<bool(PhysicsContact& contact, PhysicsContactPreSolve& solve)> onContactPreSolve;
/*
/**
* @brief Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See cpArbiter for more info
*/
std::function<void(PhysicsContact& contact, const PhysicsContactPostSolve& solve)> onContactPostSolve;
/*
* @brief it will called at two shapes separated, and only call it once.
/**
* @brief It will called at two shapes separated, and only call it once.
* onContactBegin and onContactSeperate will called in pairs.
*/
std::function<void(PhysicsContact& contact)> onContactSeperate;
@ -223,13 +245,15 @@ protected:
friend class PhysicsWorld;
};
/** this event listener only be called when bodyA and bodyB have contacts */
/** This event listener only be called when bodyA and bodyB have contacts. */
class CC_DLL EventListenerPhysicsContactWithBodies : public EventListenerPhysicsContact
{
public:
/** Create the listener. */
static EventListenerPhysicsContactWithBodies* create(PhysicsBody* bodyA, PhysicsBody* bodyB);
virtual bool hitTest(PhysicsShape* shapeA, PhysicsShape* shapeB) override;
virtual EventListenerPhysicsContactWithBodies* clone() override;
protected:
@ -241,10 +265,11 @@ protected:
virtual ~EventListenerPhysicsContactWithBodies();
};
/** this event listener only be called when shapeA and shapeB have contacts */
/** This event listener only be called when shapeA and shapeB have contacts. */
class CC_DLL EventListenerPhysicsContactWithShapes : public EventListenerPhysicsContact
{
public:
/** Create the listener. */
static EventListenerPhysicsContactWithShapes* create(PhysicsShape* shapeA, PhysicsShape* shapeB);
virtual bool hitTest(PhysicsShape* shapeA, PhysicsShape* shapeB) override;
@ -259,10 +284,11 @@ protected:
virtual ~EventListenerPhysicsContactWithShapes();
};
/** this event listener only be called when shapeA or shapeB is in the group your specified */
/** This event listener only be called when shapeA or shapeB is in the group your specified */
class CC_DLL EventListenerPhysicsContactWithGroup : public EventListenerPhysicsContact
{
public:
/** Create the listener. */
static EventListenerPhysicsContactWithGroup* create(int group);
virtual bool hitTest(PhysicsShape* shapeA, PhysicsShape* shapeB) override;
@ -276,6 +302,8 @@ protected:
virtual ~EventListenerPhysicsContactWithGroup();
};
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -34,18 +34,51 @@
NS_CC_BEGIN
/**
* @addtogroup physics
* @{
*/
/**
* A physics helper class.
*
* Support for conversion between the chipmunk types and cocos types, eg: cpVect to Vec2, cpVect to Size, cpFloat to float.
*/
class PhysicsHelper
{
public:
/** Make cpVect type convert to Vec2 type. */
static Vec2 cpv2point(const cpVect& vec) { return Vec2(vec.x, vec.y); }
/** Make Vec2 type convert to cpVect type. */
static cpVect point2cpv(const Vec2& point) { return cpv(point.x, point.y); }
/** Make cpVect type convert to Size type. */
static Size cpv2size(const cpVect& vec) { return Size(vec.x, vec.y); }
/** Make Size type convert to cpVect type. */
static cpVect size2cpv(const Size& size) { return cpv(size.width, size.height); }
/** Make cpFloat type convert to float type. */
static float cpfloat2float(cpFloat f) { return f; }
/** Make float type convert to cpFloat type. */
static cpFloat float2cpfloat(float f) { return f; }
/** Make Rect type convert to cpBB type. */
static cpBB rect2cpbb(const Rect& rect) { return cpBBNew(rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); }
/** Make cpBB type convert to Rect type. */
static Rect cpbb2rect(const cpBB& bb) { return Rect(bb.l, bb.b, bb.r - bb.l, bb.t - bb.b); }
/**
Make cpVect array convert to Vec2 array.
@param cpvs The be converted object, it's a cpVect array.
@param out The coverted object, it's a Vec2 array.
@param count It's cpvs array length.
@return The out object's pointer.
*/
static Vec2* cpvs2points(const cpVect* cpvs, Vec2* out, int count)
{
for (int i = 0; i < count; ++i)
@ -56,6 +89,14 @@ public:
return out;
}
/**
Make Vec2 array convert to cpVect array.
@param points The be converted object, it's a Vec2 array.
@param out The coverted object, it's a cpVect array.
@param count It's points array length.
@return The out object's pointer.
*/
static cpVect* points2cpvs(const Vec2* points, cpVect* out, int count)
{
for (int i = 0; i < count; ++i)
@ -67,6 +108,8 @@ public:
}
};
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -39,7 +39,12 @@ class Node;
class PhysicsBody;
class PhysicsWorld;
/*
/**
* @addtogroup physics
* @{
*/
/**
* @brief An PhysicsJoint object connects two physics bodies together.
*/
class CC_DLL PhysicsJoint
@ -49,29 +54,56 @@ protected:
virtual ~PhysicsJoint() = 0;
public:
/**Get physics body a connected to this joint.*/
inline PhysicsBody* getBodyA() const { return _bodyA; }
/**Get physics body b connected to this joint.*/
inline PhysicsBody* getBodyB() const { return _bodyB; }
/**Get the physics world.*/
inline PhysicsWorld* getWorld() const { return _world; }
/**
* Get this joint's tag.
*
* @return An interger number.
*/
inline int getTag() const { return _tag; }
/**
* Set this joint's tag.
*
* @param tag An interger number that identifies a PhysicsJoint.
*/
inline void setTag(int tag) { _tag = tag; }
/** Determines if the joint is enable. */
inline bool isEnabled() const { return _enable; }
/** Enable/Disable the joint */
/** Enable/Disable the joint. */
void setEnable(bool enable);
/** Determines if the collsion is enable. */
inline bool isCollisionEnabled() const { return _collisionEnable; }
/** Enable/disable the collision between two bodies */
/** Enable/disable the collision between two bodies. */
void setCollisionEnable(bool enable);
/** Remove the joint from the world */
/** Remove the joint from the world. */
void removeFormWorld();
/** Set the max force between two bodies */
/** Set the max force between two bodies. */
void setMaxForce(float force);
/** Get the max force setting */
/** Get the max force setting. */
float getMaxForce() const { return _maxForce; }
protected:
bool init(PhysicsBody* a, PhysicsBody* b);
bool initJoint();
/** Create constraints for this type joint */
virtual bool createConstraints() { return false; }
std::vector<cpConstraint*> _cpConstraints;
@ -92,12 +124,19 @@ protected:
friend class PhysicsDebugDraw;
};
/*
/**
* @brief A fixed joint fuses the two bodies together at a reference point. Fixed joints are useful for creating complex shapes that can be broken apart later.
*/
class CC_DLL PhysicsJointFixed : public PhysicsJoint
{
public:
/** Create a fixed joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr It's the pivot position.
@return A object pointer.
*/
static PhysicsJointFixed* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr);
virtual bool createConstraints() override;
@ -109,22 +148,54 @@ protected:
Vec2 _anchr;
};
/*
/**
* @brief A limit joint imposes a maximum distance between the two bodies, as if they were connected by a rope.
*/
class CC_DLL PhysicsJointLimit : public PhysicsJoint
{
public:
/** Create a limit joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr1 Anchr1 is the anchor point on body a.
@param anchr2 Anchr2 is the anchor point on body b.
@return A object pointer.
*/
static PhysicsJointLimit* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2);
/** Create a limit joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr1 Anchr1 is the anchor point on body a.
@param anchr2 Anchr2 is the anchor point on body b.
@param min Define the allowed min distance of the anchor points.
@param max Define the allowed max distance of the anchor points.
@return A object pointer.
*/
static PhysicsJointLimit* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2, float min, float max);
/** Get the anchor point on body a.*/
Vec2 getAnchr1() const;
/** Set the anchor point on body a.*/
void setAnchr1(const Vec2& anchr1);
/** Get the anchor point on body b.*/
Vec2 getAnchr2() const;
/** Set the anchor point on body b.*/
void setAnchr2(const Vec2& anchr2);
/** Get the allowed min distance of the anchor points.*/
float getMin() const;
/** Set the min distance of the anchor points.*/
void setMin(float min);
/** Get the allowed max distance of the anchor points.*/
float getMax() const;
/** Set the max distance of the anchor points.*/
void setMax(float max);
virtual bool createConstraints() override;
@ -139,13 +210,29 @@ protected:
float _max;
};
/*
/**
* @brief A pin joint allows the two bodies to independently rotate around the anchor point as if pinned together.
*/
class CC_DLL PhysicsJointPin : public PhysicsJoint
{
public:
/** Create a pin joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param pivot It's the pivot position.
@return A object pointer.
*/
static PhysicsJointPin* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& pivot);
/** Create a pin joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr1 Anchr1 is the anchor point on body a.
@param anchr2 Anchr2 is the anchor point on body b.
@return A object pointer.
*/
static PhysicsJointPin* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2);
virtual bool createConstraints() override;
@ -163,9 +250,19 @@ protected:
class CC_DLL PhysicsJointDistance : public PhysicsJoint
{
public:
/** Create a fixed distance joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr1 Anchr1 is the anchor point on body a.
@param anchr2 Anchr2 is the anchor point on body b.
@return A object pointer.
*/
static PhysicsJointDistance* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2);
/** Get the distance of the anchor points.*/
float getDistance() const;
/** Set the distance of the anchor points.*/
void setDistance(float distance);
virtual bool createConstraints() override;
@ -181,17 +278,48 @@ protected:
class CC_DLL PhysicsJointSpring : public PhysicsJoint
{
public:
/** Create a fixed distance joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param anchr1 Anchr1 is the anchor point on body a.
@param anchr2 Anchr2 is the anchor point on body b.
@param stiffness It's the spring constant.
@param damping It's how soft to make the damping of the spring.
@return A object pointer.
*/
static PhysicsJointSpring* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& anchr1, const Vec2& anchr2, float stiffness, float damping);
/** Get the anchor point on body a.*/
Vec2 getAnchr1() const;
/** Set the anchor point on body a.*/
void setAnchr1(const Vec2& anchr1);
/** Get the anchor point on body b.*/
Vec2 getAnchr2() const;
/** Set the anchor point on body b.*/
void setAnchr2(const Vec2& anchr2);
/** Get the distance of the anchor points.*/
float getRestLength() const;
/** Set the distance of the anchor points.*/
void setRestLength(float restLength);
/** Get the spring constant.*/
float getStiffness() const;
/** Set the spring constant.*/
void setStiffness(float stiffness);
/** Get the spring soft constant.*/
float getDamping() const;
/** Set the spring soft constant.*/
void setDamping(float damping);
virtual bool createConstraints() override;
protected:
@ -204,18 +332,39 @@ protected:
float _damping;
};
/** Attach body a to a line, and attach body b to a dot */
/** Attach body a to a line, and attach body b to a dot. */
class CC_DLL PhysicsJointGroove : public PhysicsJoint
{
public:
/** Create a groove joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param grooveA The line begin position.
@param grooveB The line end position.
@param anchr2 Anchr2 is the anchor point on body b.
@return A object pointer.
*/
static PhysicsJointGroove* construct(PhysicsBody* a, PhysicsBody* b, const Vec2& grooveA, const Vec2& grooveB, const Vec2& anchr2);
/** Get the line begin position*/
Vec2 getGrooveA() const;
/** Set the line begin position*/
void setGrooveA(const Vec2& grooveA);
/** Get the line end position*/
Vec2 getGrooveB() const;
/** Set the line end position*/
void setGrooveB(const Vec2& grooveB);
/** Get the anchor point on body b.*/
Vec2 getAnchr2() const;
/** Set the anchor point on body b.*/
void setAnchr2(const Vec2& anchr2);
virtual bool createConstraints() override;
protected:
@ -227,18 +376,38 @@ protected:
Vec2 _anchr2;
};
/** Likes a spring joint, but works with rotary */
/** Likes a spring joint, but works with rotary. */
class CC_DLL PhysicsJointRotarySpring : public PhysicsJoint
{
public:
/** Create a damped rotary spring joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param stiffness It's the spring constant.
@param damping It's how soft to make the damping of the spring.
@return A object pointer.
*/
static PhysicsJointRotarySpring* construct(PhysicsBody* a, PhysicsBody* b, float stiffness, float damping);
/** Get the relative angle in radians from the body a to b.*/
float getRestAngle() const;
/** Set the relative angle in radians from the body a to b.*/
void setRestAngle(float restAngle);
/** Get the spring constant.*/
float getStiffness() const;
/** Set the spring constant.*/
void setStiffness(float stiffness);
/** Get the spring soft constant.*/
float getDamping() const;
/** Set the spring soft constant.*/
void setDamping(float damping);
virtual bool createConstraints() override;
protected:
@ -249,17 +418,40 @@ protected:
float _damping;
};
/** Likes a limit joint, but works with rotary */
/** Likes a limit joint, but works with rotary. */
class CC_DLL PhysicsJointRotaryLimit : public PhysicsJoint
{
public:
/** Create a limit rotary joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param min It's min rotation limit in radians.
@param max It's max rotation limit in radians.
@return A object pointer.
*/
static PhysicsJointRotaryLimit* construct(PhysicsBody* a, PhysicsBody* b, float min, float max);
/** Create a limit rotary joint.
@param a A is the body to connect.
@param b B is the body to connect.
@return A object pointer.
*/
static PhysicsJointRotaryLimit* construct(PhysicsBody* a, PhysicsBody* b);
/** Get the min rotation limit.*/
float getMin() const;
/** Set the min rotation limit.*/
void setMin(float min);
/** Get the max rotation limit.*/
float getMax() const;
/** Set the max rotation limit.*/
void setMax(float max);
virtual bool createConstraints() override;
protected:
@ -274,13 +466,32 @@ protected:
class CC_DLL PhysicsJointRatchet : public PhysicsJoint
{
public:
/** Create a ratchet joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param phase Phase is the initial offset to use when deciding where the ratchet angles are.
@param ratchet Ratchet is the distance between clicks.
@return A object pointer.
*/
static PhysicsJointRatchet* construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratchet);
/** Get the ratchet angle.*/
float getAngle() const;
/** Set the ratchet angle.*/
void setAngle(float angle);
/** Get the initial offset.*/
float getPhase() const;
/** Set the initial offset.*/
void setPhase(float phase);
/** Get the distance between “clicks”.*/
float getRatchet() const;
/** Set the distance between “clicks”.*/
void setRatchet(float ratchet);
virtual bool createConstraints() override;
@ -296,11 +507,26 @@ protected:
class CC_DLL PhysicsJointGear : public PhysicsJoint
{
public:
/** Create a gear joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param phase Phase is the initial angular offset of the two bodies.
@param ratio Ratio is always measured in absolute terms.
@return A object pointer.
*/
static PhysicsJointGear* construct(PhysicsBody* a, PhysicsBody* b, float phase, float ratio);
/** Get the angular offset of the two bodies.*/
float getPhase() const;
/** Set the angular offset of the two bodies.*/
void setPhase(float phase);
/** Get the ratio.*/
float getRatio() const;
/** Set the ratio.*/
void setRatio(float ratchet);
virtual bool createConstraints() override;
@ -313,13 +539,23 @@ protected:
float _ratio;
};
/** Keeps the relative angular velocity of a pair of bodies constant */
/** Keeps the relative angular velocity of a pair of bodies constant. */
class CC_DLL PhysicsJointMotor : public PhysicsJoint
{
public:
/** Create a motor joint.
@param a A is the body to connect.
@param b B is the body to connect.
@param rate Rate is the desired relative angular velocity.
@return A object pointer.
*/
static PhysicsJointMotor* construct(PhysicsBody* a, PhysicsBody* b, float rate);
/** Get the relative angular velocity.*/
float getRate() const;
/** Set the relative angular velocity.*/
void setRate(float rate);
virtual bool createConstraints() override;
@ -330,6 +566,8 @@ protected:
float _rate;
};
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -58,6 +58,11 @@ typedef struct CC_DLL PhysicsMaterial
const PhysicsMaterial PHYSICSSHAPE_MATERIAL_DEFAULT;
/**
* @addtogroup physics
* @{
*/
/**
* @brief A shape for body. You do not create PhysicsWorld objects directly, instead, you can view PhysicsBody to see how to create it.
*/
@ -77,74 +82,246 @@ public:
};
public:
/** Get the body that this shape attaches */
/**
* Get the body that this shape attaches.
*
* @return A PhysicsBody object pointer.
*/
inline PhysicsBody* getBody() const { return _body; }
/** Return the type of this shape */
/**
* Return this shape's type.
*
* @return A Type object.
*/
inline Type getType() const { return _type; }
/** return the area of this shape */
/**
* Return this shape's area.
*
* @return A float number.
*/
inline float getArea() const { return _area; }
/** get moment */
/**
* Get this shape's moment.
*
* @return A float number.
*/
inline float getMoment() const { return _moment; }
/** Set moment, it will change the body's moment this shape attaches */
/**
* Set this shape's moment.
*
* It will change the body's moment this shape attaches.
*
* @param moment A float number.
*/
void setMoment(float moment);
/**
* Set this shape's tag.
*
* @param tag An interger number that identifies a shape object.
*/
inline void setTag(int tag) { _tag = tag; }
/**
* Get this shape's tag.
*
* @return An interger number.
*/
inline int getTag() const { return _tag; }
/** get mass */
/**
* Get the mass of this shape.
*
* @return A float number.
*/
inline float getMass() const { return _mass; }
/** Set mass, it will change the body's mass this shape attaches */
/**
* Set this shape's mass.
*
* It will change the body's mass this shape attaches.
*
* @param mass A float number.
*/
void setMass(float mass);
/**
* Get this shape's density.
*
* @return A float number.
*/
inline float getDensity() const { return _material.density; }
/**
* Set this shape's density.
*
* It will change the body's mass this shape attaches.
*
* @param density A float number.
*/
void setDensity(float density);
/**
* Get this shape's restitution.
*
* @return A float number.
*/
inline float getRestitution() const { return _material.restitution; }
/**
* Set this shape's restitution.
*
* It will change the shape's elasticity.
*
* @param restitution A float number.
*/
void setRestitution(float restitution);
/**
* Get this shape's friction.
*
* @return A float number.
*/
inline float getFriction() const { return _material.friction; }
/**
* Set this shape's friction.
*
* It will change the shape's friction.
*
* @param friction A float number.
*/
void setFriction(float friction);
/**
* Get this shape's PhysicsMaterial object.
*
* @return A PhysicsMaterial object reference.
*/
const PhysicsMaterial& getMaterial() const { return _material; }
/**
* Set this shape's material.
*
* It will change the shape's mass, elasticity and friction.
*
* @param material A PhysicsMaterial object.
*/
void setMaterial(const PhysicsMaterial& material);
/** Calculate the default moment value */
/**
* Calculate the default moment value.
*
* This function should be overrided in inherit classes.
* @return A float number, equals 0.0.
*/
virtual float calculateDefaultMoment() { return 0.0f; }
/** Get offset */
/**
* Get this shape's position offset.
*
* This function should be overrided in inherit classes.
* @return A Vec2 object.
*/
virtual Vec2 getOffset() { return Vec2::ZERO; }
/** Get center of this shape */
/**
* Get this shape's center position.
*
* This function should be overrided in inherit classes.
* @return A Vec2 object.
*/
virtual Vec2 getCenter() { return getOffset(); }
/** Test point is in shape or not */
/**
* Test point is inside this shape or not.
*
* @param point A Vec2 object.
* @return A bool object.
*/
bool containsPoint(const Vec2& point) const;
/** move the points to the center */
/**
* Move the points to the center.
*
* @param points A Vec2 object pointer.
* @param count An interger number.
* @param center A Vec2 object, default value is Vec2(0,0).
*/
static void recenterPoints(Vec2* points, int count, const Vec2& center = Vec2::ZERO);
/** get center of the polyon points */
/**
* Get center of the polyon points.
*
* @param points A Vec2 object pointer.
* @param count An interger number.
* @return A Vec2 object.
*/
static Vec2 getPolyonCenter(const Vec2* points, int count);
/**
* A mask that defines which categories this physics body belongs to.
* Set a mask that defines which categories this physics body belongs to.
*
* Every physics body in a scene can be assigned to up to 32 different categories, each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties, you define which physics bodies interact with each other and when your game is notified of these interactions.
* The default value is 0xFFFFFFFF (all bits set).
* @param bitmask An interger number, the default value is 0xFFFFFFFF (all bits set).
*/
inline void setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; }
/**
* Get a mask that defines which categories this physics body belongs to.
*
* @return An interger number.
*/
inline int getCategoryBitmask() const { return _categoryBitmask; }
/**
* A mask that defines which categories of bodies cause intersection notifications with this physics body.
*
* When two bodies share the same space, each bodys category mask is tested against the other bodys contact mask by performing a logical AND operation. If either comparison results in a non-zero value, an PhysicsContact object is created and passed to the physics worlds delegate. For best performance, only set bits in the contacts mask for interactions you are interested in.
* The default value is 0x00000000 (all bits cleared).
* @param bitmask An interger number, the default value is 0x00000000 (all bits cleared).
*/
inline void setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; }
/**
* Get a mask that defines which categories of bodies cause intersection notifications with this physics body.
*
* @return An interger number.
*/
inline int getContactTestBitmask() const { return _contactTestBitmask; }
/**
* A mask that defines which categories of physics bodies can collide with this physics body.
*
* When two physics bodies contact each other, a collision may occur. This bodys collision mask is compared to the other bodys category mask by performing a logical AND operation. If the result is a non-zero value, then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example, you might use this to avoid collision calculations that would make negligible changes to a bodys velocity.
* The default value is 0xFFFFFFFF (all bits set).
* @param bitmask An interger number, the default value is 0xFFFFFFFF (all bits set).
*/
inline void setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; }
/**
* Get a mask that defines which categories of physics bodies can collide with this physics body.
*
* @return An interger number.
*/
inline int getCollisionBitmask() const { return _collisionBitmask; }
/**
* set the group of body
* Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index)
* it have high priority than bit masks
* Set the group of body.
*
* Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index).
* @param group An interger number, it have high priority than bit masks.
*/
void setGroup(int group);
/**
* Get the group of body.
*
* @return An interger number.
*/
inline int getGroup() { return _group; }
protected:
@ -186,17 +363,57 @@ protected:
friend class PhysicsDebugDraw;
};
/** A circle shape */
/** A circle shape. */
class CC_DLL PhysicsShapeCircle : public PhysicsShape
{
public:
/**
* Creates a PhysicsShapeCircle with specified value.
*
* @param radius A float number, it is the circle's radius.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsShapeCircle object pointer.
*/
static PhysicsShapeCircle* create(float radius, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Vec2& offset = Vec2(0, 0));
/**
* Calculate the area of a circle with specified radius.
*
* @param radius A float number
* @return A float number
*/
static float calculateArea(float radius);
/**
* Calculate the moment of a circle with specified value.
*
* @param mass A float number
* @param radius A float number
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return A float number
*/
static float calculateMoment(float mass, float radius, const Vec2& offset = Vec2::ZERO);
/**
* Calculate the moment for a circle.
*
* @return A float number.
*/
virtual float calculateDefaultMoment() override;
/**
* Get the circle's radius.
*
* @return A float number.
*/
float getRadius() const;
/**
* Get this circle's position offset.
*
* @return A Vec2 object.
*/
virtual Vec2 getOffset() override;
protected:
@ -209,19 +426,75 @@ protected:
virtual ~PhysicsShapeCircle();
};
/** A polygon shape */
/** A polygon shape. */
class CC_DLL PhysicsShapePolygon : public PhysicsShape
{
public:
/**
* Creates a PhysicsShapePolygon with specified value.
*
* @param points A Vec2 object pointer, it is an array of Vec2.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsShapePolygon object pointer.
*/
static PhysicsShapePolygon* create(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/**
* Calculate the area of a polygon with specified value.
*
* @param points A Vec2 object pointer, it is an array of Vec2.
* @param count An interger number, contains the count of the points array.
* @return A float number.
*/
static float calculateArea(const Vec2* points, int count);
/**
* Calculate the moment of a polygon with specified value.
*
* @param mass A float number
* @param points A Vec2 object pointer, it is an array of Vec2.
* @param count An interger number, contains the count of the points array.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return A float number
*/
static float calculateMoment(float mass, const Vec2* points, int count, const Vec2& offset = Vec2::ZERO);
/**
* Calculate the moment for a polygon.
*
* @return A float number.
*/
float calculateDefaultMoment() override;
/**
* Get a point of this polygon's points array.
*
* @param i A index of this polygon's points array.
* @return A point value.
*/
Vec2 getPoint(int i) const;
/**
* Get this polygon's points array.
*
* @param outPoints A Vec2 array pointer.
*/
void getPoints(Vec2* outPoints) const;
/**
* Get this polygon's points array count.
*
* @preturn An interger number.
*/
int getPointsCount() const;
/**
* Get this polygon's center position.
*
* @return A Vec2 object.
*/
virtual Vec2 getCenter() override;
protected:
bool init(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
@ -233,13 +506,32 @@ protected:
virtual ~PhysicsShapePolygon();
};
/** A box shape */
/** A box shape. */
class CC_DLL PhysicsShapeBox : public PhysicsShapePolygon
{
public:
/**
* Creates a PhysicsShapeBox with specified value.
*
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsShapeBox object pointer.
*/
static PhysicsShapeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, const Vec2& offset = Vec2::ZERO);
/**
* Get this box's width and height.
*
* @preturn An Size object.
*/
Size getSize() const;
/**
* Get this box's position offset.
*
* @return A Vec2 object.
*/
virtual Vec2 getOffset() override { return getCenter(); }
protected:
@ -250,14 +542,40 @@ protected:
virtual ~PhysicsShapeBox();
};
/** A segment shape */
/** A segment shape. */
class CC_DLL PhysicsShapeEdgeSegment : public PhysicsShape
{
public:
/**
* Creates a PhysicsShapeEdgeSegment with specified value.
*
* @param a It's the edge's begin position.
* @param b It's the edge's end position.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsShapeEdgeSegment object pointer.
*/
static PhysicsShapeEdgeSegment* create(const Vec2& a, const Vec2& b, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1);
/**
* Get this edge's begin position.
*
* @return A Vec2 object.
*/
Vec2 getPointA() const;
/**
* Get this edge's end position.
*
* @return A Vec2 object.
*/
Vec2 getPointB() const;
/**
* Get this edge's center position.
*
* @return A Vec2 object.
*/
virtual Vec2 getCenter() override;
protected:
@ -271,13 +589,40 @@ protected:
friend class PhysicsBody;
};
/** An edge polygon shape */
/** An edge polygon shape. */
class CC_DLL PhysicsShapeEdgePolygon : public PhysicsShape
{
public:
/**
* Creates a PhysicsShapeEdgePolygon with specified value.
*
* @param points A Vec2 object pointer, it contains an array of points.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsShapeEdgePolygon object pointer.
*/
static PhysicsShapeEdgePolygon* create(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1);
/**
* Get this polygon's center position.
*
* @return A Vec2 object.
*/
virtual Vec2 getCenter() override;
/**
* Get this polygon's points array.
*
* @param outPoints A Vec2 array pointer.
*/
void getPoints(Vec2* outPoints) const;
/**
* Get this polygon's points array count.
*
* @preturn An interger number.
*/
int getPointsCount() const;
protected:
@ -291,11 +636,26 @@ protected:
friend class PhysicsBody;
};
/** An edge box shape */
/** An edge box shape. */
class CC_DLL PhysicsShapeEdgeBox : public PhysicsShapeEdgePolygon
{
public:
/**
* Creates a PhysicsShapeEdgeBox with specified value.
*
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @param offset A Vec2 object, it is the offset from the bodys center of gravity in body local coordinates.
* @return An autoreleased PhysicsShapeEdgeBox object pointer.
*/
static PhysicsShapeEdgeBox* create(const Size& size, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 0, const Vec2& offset = Vec2::ZERO);
/**
* Get this box's position offset.
*
* @return A Vec2 object.
*/
virtual Vec2 getOffset() override { return getCenter(); }
protected:
@ -308,13 +668,40 @@ protected:
friend class PhysicsBody;
};
/** a chain shape */
/** A chain shape. */
class CC_DLL PhysicsShapeEdgeChain : public PhysicsShape
{
public:
/**
* Creates a PhysicsShapeEdgeChain with specified value.
*
* @param points A Vec2 object pointer, it contains an array of points.
* @param count An interger number, contains the count of the points array.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param border It's a edge's border width.
* @return An autoreleased PhysicsShapeEdgeChain object pointer.
*/
static PhysicsShapeEdgeChain* create(const Vec2* points, int count, const PhysicsMaterial& material = PHYSICSSHAPE_MATERIAL_DEFAULT, float border = 1);
/**
* Get this chain's center position.
*
* @return A Vec2 object.
*/
virtual Vec2 getCenter() override;
/**
* Get this chain's points array.
*
* @param outPoints A Vec2 array pointer.
*/
void getPoints(Vec2* outPoints) const;
/**
* Get this chain's points array count.
*
* @preturn An interger number.
*/
int getPointsCount() const;
protected:
@ -328,6 +715,8 @@ protected:
friend class PhysicsBody;
};
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -80,6 +80,12 @@ typedef std::function<bool(PhysicsWorld&, PhysicsShape&, void*)> PhysicsQueryRec
typedef PhysicsQueryRectCallbackFunc PhysicsQueryPointCallbackFunc;
/**
* @addtogroup physics
* @{
*/
/**
* @class PhysicsWorld CCPhysicsWorld.h
* @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object.
*/
class CC_DLL PhysicsWorld
@ -92,82 +98,231 @@ public:
static const int DEBUGDRAW_ALL; ///< draw all
public:
/** Adds a joint to the physics world.*/
/**
* Adds a joint to this physics world.
*
* This joint will be added to this physics world at next frame.
* @attention If this joint is already added to another physics world, it will be removed from that world first and then add to this world.
* @param joint A pointer to an existing PhysicsJoint object.
*/
virtual void addJoint(PhysicsJoint* joint);
/** Remove a joint from physics world.*/
/**
* Remove a joint from this physics world.
*
* If this world is not locked, the joint is removed immediately, otherwise at next frame.
* If this joint is connected with a body, it will be removed from the body also.
* @param joint A pointer to an existing PhysicsJoint object.
* @param destroy true this joint will be destroyed after remove from this world, false otherwise.
*/
virtual void removeJoint(PhysicsJoint* joint, bool destroy = true);
/** Remove all joints from physics world.*/
/**
* Remove all joints from this physics world.
*
* @attention This function is invoked in the destructor of this physics world, you do not use this api in common.
* @param destroy true all joints will be destroyed after remove from this world, false otherwise.
*/
virtual void removeAllJoints(bool destroy = true);
/** Remove a body from physics world. */
/**
* Remove a body from this physics world.
*
* If this world is not locked, the body is removed immediately, otherwise at next frame.
* @attention If this body has joints, those joints will be removed also.
* @param body A pointer to an existing PhysicsBody object.
*/
virtual void removeBody(PhysicsBody* body);
/** Remove body by tag. */
/**
* Remove body by tag.
*
* If this world is not locked, the object is removed immediately, otherwise at next frame.
* @attention If this body has joints, those joints will be removed also.
* @param tag An interger number that identifies a PhysicsBody object.
*/
virtual void removeBody(int tag);
/** Remove all bodies from physics world. */
/**
* Remove all bodies from physics world.
*
* If this world is not locked, those body are removed immediately, otherwise at next frame.
*/
virtual void removeAllBodies();
/** Searches for physics shapes that intersects the ray. */
/**
* Searches for physics shapes that intersects the ray.
*
* Query this physics world along the line segment from start to end.
* @param func Func is called for each shape found.
* @param start A Vec2 object contains the begin position of the ray.
* @param end A Vec2 object contains the end position of the ray.
* @param data User defined data, it is passed to func.
*/
void rayCast(PhysicsRayCastCallbackFunc func, const Vec2& start, const Vec2& end, void* data);
/** Searches for physics shapes that contains in the rect. */
/**
* Searches for physics shapes that contains in the rect.
*
* Query this physics world to find all shapes overlap rect.
* @param func Func is called for each shape whose bounding box overlaps rect.
* @param rect A Rect object contains a rectangle's x, y, width and height.
* @param data User defined data, it is passed to func.
*/
void queryRect(PhysicsQueryRectCallbackFunc func, const Rect& rect, void* data);
/** Searches for physics shapes that contains the point. */
/**
* Searches for physics shapes that contains the point.
*
* @attention The point must lie inside a shape.
* @param func Func is called for each shape contains the point.
* @param point A Vec2 object contains the position of the point.
* @param data User defined data, it is passed to func.
*/
void queryPoint(PhysicsQueryPointCallbackFunc func, const Vec2& point, void* data);
/** Get phsyics shapes that contains the point. */
/**
* Get phsyics shapes that contains the point.
*
* All shapes contains the point will be pushed in a Vector<PhysicsShape*> object.
* @attention The point must lie inside a shape.
* @param point A Vec2 object contains the position of the point.
* @return A Vector<PhysicsShape*> object contains all found PhysicsShape pointer.
*/
Vector<PhysicsShape*> getShapes(const Vec2& point) const;
/** return physics shape that contains the point. */
/**
* Get the nearest phsyics shape that contains the point.
*
* Query this physics world at point and return the closest shape.
* @param point A Vec2 object contains the position of the point.
* @return A PhysicsShape object pointer or nullptr if no shapes were found
*/
PhysicsShape* getShape(const Vec2& point) const;
/** Get all the bodys that in the physics world. */
/**
* Get all the bodys that in this physics world.
*
* @return A Vector<PhysicsBody*>& object contains all bodies in this physics world.
*/
const Vector<PhysicsBody*>& getAllBodies() const;
/** Get body by tag */
/**
* Get a body by tag.
*
* @param tag An interger number that identifies a PhysicsBody object.
* @return A PhysicsBody object pointer or nullptr if no shapes were found.
*/
PhysicsBody* getBody(int tag) const;
/** Get scene contain this physics world */
inline Scene& getScene() const { return *_scene; }
/** get the gravity value */
inline Vect getGravity() const { return _gravity; }
/** set the gravity value */
void setGravity(const Vect& gravity);
/**
* Set the speed of physics world, speed is the rate at which the simulation executes. default value is 1.0
* Note: if you setAutoStep(false), this won't work.
* Get a scene contain this physics world.
*
* @attention This value is initialized in constructor
* @return A Scene object reference.
*/
inline Scene& getScene() const { return *_scene; }
/**
* Get the gravity value of this physics world.
*
* @return A Vect object.
*/
inline Vect getGravity() const { return _gravity; }
/**
* set the gravity value of this physics world.
*
* @param gravity A gravity value of this physics world.
*/
void setGravity(const Vect& gravity);
/**
* Set the speed of this physics world.
*
* @attention if you setAutoStep(false), this won't work.
* @param speed A float number. Speed is the rate at which the simulation executes. default value is 1.0.
*/
inline void setSpeed(float speed) { if(speed >= 0.0f) { _speed = speed; } }
/** get the speed of physics world */
inline float getSpeed() { return _speed; }
/**
* set the update rate of physics world, update rate is the value of EngineUpdateTimes/PhysicsWorldUpdateTimes.
* set it higher can improve performance, set it lower can improve accuracy of physics world simulation.
* default value is 1.0
* Note: if you setAutoStep(false), this won't work.
* Get the speed of this physics world.
*
* @return A float number.
*/
inline float getSpeed() { return _speed; }
/**
* Set the update rate of this physics world
*
* Update rate is the value of EngineUpdateTimes/PhysicsWorldUpdateTimes.
* Set it higher can improve performance, set it lower can improve accuracy of physics world simulation.
* @attention if you setAutoStep(false), this won't work.
* @param rate An interger number, default value is 1.0.
*/
inline void setUpdateRate(int rate) { if(rate > 0) { _updateRate = rate; } }
/** get the update rate */
/**
* Get the update rate of this physics world.
*
* @return An interger number.
*/
inline int getUpdateRate() { return _updateRate; }
/**
* set the number of substeps in an update of the physics world.
*
* One physics update will be divided into several substeps to increase its accuracy.
* default value is 1
* @param steps An interger number, default value is 1.
*/
void setSubsteps(int steps);
/** get the number of substeps */
/**
* Get the number of substeps of this physics world.
*
* @return An interger number.
*/
inline int getSubsteps() const { return _substeps; }
/** set the debug draw mask */
/**
* Set the debug draw mask of this physics world.
*
* This physics world will draw shapes and joints by DrawNode acoording to mask.
* @param mask Mask has four value:DEBUGDRAW_NONE, DEBUGDRAW_SHAPE, DEBUGDRAW_JOINT, DEBUGDRAW_CONTACT and DEBUGDRAW_ALL, default is DEBUGDRAW_NONE
*/
void setDebugDrawMask(int mask);
/** get the bebug draw mask */
/**
* Get the bebug draw mask.
*
* @return An interger number.
*/
inline int getDebugDrawMask() { return _debugDrawMask; }
/**
* To control the step of physics, if you want control it by yourself( fixed-timestep for example ), you can set this to false and call step by yourself.
* Defaut value is true.
* Note: if you set auto step to false, setSpeed setSubsteps and setUpdateRate won't work, you need to control the time step by yourself.
* To control the step of physics.
*
* If you want control it by yourself( fixed-timestep for example ), you can set this to false and call step by yourself.
* @attention If you set auto step to false, setSpeed setSubsteps and setUpdateRate won't work, you need to control the time step by yourself.
* @param autoStep A bool object, defaut value is true.
*/
void setAutoStep(bool autoStep){ _autoStep = autoStep; }
/** Get the auto step */
bool isAutoStep() { return _autoStep; }
/**
* The step for physics world, The times passing for simulate the physics.
* Note: you need to setAutoStep(false) first before it can work.
* Get the auto step of this physics world.
*
* @return A bool object.
*/
bool isAutoStep() { return _autoStep; }
/**
* The step for physics world.
*
* The times passing for simulate the physics.
* @attention You need to setAutoStep(false) first before it can work.
* @param delta A float number.
*/
void step(float delta);
@ -234,7 +389,10 @@ protected:
friend class PhysicsDebugDraw;
};
/** A physics helper class. Draw physics shape, joint in debug mode.
* You do not create PhysicsDebugDraw objects directly; Instead, you can activate it by PhysicsWorld::setDebugDrawMask.
*/
class CC_DLL PhysicsDebugDraw
{
protected:
@ -256,6 +414,7 @@ protected:
};
extern const float CC_DLL PHYSICS_INFINITY;
/** @} */
NS_CC_END
#endif // CC_USE_PHYSICS

View File

@ -41,22 +41,23 @@ class CC_DLL ApplicationProtocol
{
public:
// Since WINDOWS and ANDROID are defined as macros, we could not just use these keywords in enumeration(Platform).
// Therefore, 'OS_' prefix is added to avoid conflicts with the definitions of system macros.
/** Since WINDOWS and ANDROID are defined as macros, we could not just use these keywords in enumeration(Platform).
* Therefore, 'OS_' prefix is added to avoid conflicts with the definitions of system macros.
*/
enum class Platform
{
OS_WINDOWS,
OS_LINUX,
OS_MAC,
OS_ANDROID,
OS_IPHONE,
OS_IPAD,
OS_BLACKBERRY,
OS_NACL,
OS_EMSCRIPTEN,
OS_TIZEN,
OS_WINRT,
OS_WP8
OS_WINDOWS,/** Windows */
OS_LINUX,/** Linux */
OS_MAC,/** Mac*/
OS_ANDROID,/** Android */
OS_IPHONE,/** Iphone */
OS_IPAD,/** Ipad */
OS_BLACKBERRY,/** BLACKBERRY */
OS_NACL,/** Nacl */
OS_EMSCRIPTEN,/** Emscripten */
OS_TIZEN,/** Tizen */
OS_WINRT,/** Winrt */
OS_WP8/** WP8 */
};
/**
@ -67,77 +68,78 @@ public:
#if CC_ENABLE_SCRIPT_BINDING
ScriptEngineManager::destroyInstance();
#endif
// clean auto release pool
/** clean auto release pool. */
PoolManager::destroyInstance();
}
/**
@brief Implement Director and Scene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
* @brief Implement Director and Scene init code here.
* @return true Initialize success, app continue.
* @return false Initialize failed, app terminate.
* @js NA
* @lua NA
*/
virtual bool applicationDidFinishLaunching() = 0;
/**
@brief This function will be called when the application enters background.
* @brief This function will be called when the application enters background.
* @js NA
* @lua NA
*/
virtual void applicationDidEnterBackground() = 0;
/**
@brief This function will be called when the application enters foreground.
* @brief This function will be called when the application enters foreground.
* @js NA
* @lua NA
*/
virtual void applicationWillEnterForeground() = 0;
/**
@brief Callback by Director for limit FPS.
@param interval The time, expressed in seconds, between current frame and next.
* @brief Callback by Director for limit FPS.
* @param interval The time, expressed in seconds, between current frame and next.
* @js NA
* @lua NA
*/
virtual void setAnimationInterval(double interval) = 0;
//subclass override the function to set OpenGL context attribution instead of use default value
//and now can only set six attributions:redBits,greenBits,blueBits,alphaBits,depthBits,stencilBits
//default value are(5,6,5,0,16,0), usually use as follows:
/*void AppDelegate::initGLContextAttrs(){
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}*/
/** Subclass override the function to set OpenGL context attribution instead of use default value.
* And now can only set six attributions:redBits,greenBits,blueBits,alphaBits,depthBits,stencilBits.
* Default value are(5,6,5,0,16,0), usually use as follows:
* void AppDelegate::initGLContextAttrs(){
* GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
* GLView::setGLContextAttrs(glContextAttrs);
* }
*/
virtual void initGLContextAttrs() {}
/**
@brief Get current language config
@return Current language config
@brief Get current language config.
@return Current language config.
* @js NA
* @lua NA
*/
virtual LanguageType getCurrentLanguage() = 0;
/**
@brief Get current language iso 639-1 code
@return Current language iso 639-1 code
@brief Get current language iso 639-1 code.
@return Current language iso 639-1 code.
* @js NA
* @lua NA
*/
virtual const char * getCurrentLanguageCode() = 0;
/**
@brief Get target platform
@brief Get target platform.
* @js NA
* @lua NA
*/
virtual Platform getTargetPlatform() = 0;
/**
@brief Open url in default browser
@brief Open url in default browser.
@param String with url to open.
@return true if the resource located by the URL was successfully opened; otherwise false.
@return True if the resource located by the URL was successfully opened; otherwise false.
* @js NA
* @lua NA
*/
@ -145,7 +147,7 @@ public:
};
// end of platform group
/// @}
/** @} */
NS_CC_END

View File

@ -260,8 +260,17 @@ public class Cocos2dxHttpURLConnection
}
static byte[] getResponseContent(HttpURLConnection http) {
try {
DataInputStream in = new DataInputStream(http.getInputStream());
DataInputStream in;
try {
in = new DataInputStream(http.getInputStream());
} catch (IOException e) {
in = new DataInputStream(http.getErrorStream());
} catch (Exception e) {
Log.e("Cocos2dxHttpURLConnection exception", e.toString());
return null;
}
try {
byte[] buffer = new byte[1024];
int size = 0;
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
@ -272,12 +281,13 @@ public class Cocos2dxHttpURLConnection
byte retbuffer[] = bytestream.toByteArray();
bytestream.close();
return retbuffer;
} catch (Exception e) {
Log.e("Cocos2dxHttpURLConnection exception", e.toString());
}
} catch (Exception e) {
Log.e("Cocos2dxHttpURLConnection exception", e.toString());
}
return null;
}
static int getResponseCode(HttpURLConnection http) {
int code = 0;
try {

File diff suppressed because it is too large Load Diff

View File

@ -52,9 +52,7 @@ const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV = "ShaderPo
const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
const char* GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE = "ShaderPositionColorTexAsPointsize";
const char* GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP = "ShaderPositionColor_noMVP";
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || defined(WP8_SHADER_COMPILER)
const char* GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP_GRAYSCALE = "ShaderPositionColor_noMVP_GrayScale";
#endif
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR = "ShaderPositionTexture_uColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTextureA8Color";

View File

@ -245,13 +245,6 @@ void GLProgramCache::loadDefaultGLPrograms()
p = new GLProgram();
loadDefaultGLProgram(p, kShaderType_3DParticleTex);
_programs.insert(std::make_pair(GLProgram::SHADER_3D_PARTICLE_TEXTURE, p));
#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || defined(WP8_SHADER_COMPILER)
p = new GLProgram();
loadDefaultGLProgram(p, kShaderType_PositionColor_noMVP_GrayScale);
_programs.insert(std::make_pair(GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP_GRAYSCALE, p));
#endif
}
void GLProgramCache::reloadDefaultGLPrograms()

View File

@ -70,7 +70,7 @@ public:
void execute();
//used for bath
//used for batch
void preBatchDraw();
void batchDraw();
void postBatchDraw();

View File

@ -36,6 +36,7 @@ class EventListenerCustom;
/**
VertexBuffer is an abstraction of low level openGL Vertex Buffer Object.
It is used to save an array of vertices.
*@js NA
*/
class CC_DLL VertexBuffer : public Ref
{
@ -133,6 +134,7 @@ public:
/**
IndexBuffer is an abstraction of low level openGL Buffer Object.
It used to save an array of indices.
@js NA
*/
class CC_DLL IndexBuffer : public Ref
{

View File

@ -42,6 +42,7 @@ glVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized
_offset is used to compute the start offset in a interleaved array, take a V3F_C4B_T2F array,
offset of vertex will be 0, offset of color would be 0 + sizeof(float) * 3 = 12,
offset of texture coord would be 12 + sizeof(char) * 4 = 16.
@js NA
*/
struct CC_DLL VertexStreamAttribute
{
@ -101,6 +102,7 @@ struct CC_DLL VertexStreamAttribute
VertexData is a class used for specify input streams for GPU rendering pipeline,
a VertexData will be composed by several streams, every stream will contain a VertexStreamAttribute
and the binding VertexBuffer. Streams will be identified by semantic.
@js NA
*/
class CC_DLL VertexData : public Ref

View File

@ -103,7 +103,8 @@
--------------------------------
-- Returns a new action that performs the exactly the reverse action. <br>
-- return A new action that performs the exactly the reverse action.
-- return A new action that performs the exactly the reverse action.<br>
-- js NA
-- @function [parent=#Action] reverse
-- @param self
-- @return Action#Action ret (return value: cc.Action)

View File

@ -76,7 +76,8 @@
-- - If you are running 1 Sequence of 7 actions, it will return 1.<br>
-- - If you are running 7 Sequences of 2 actions, it will return 7.<br>
-- param target A certain target.<br>
-- return The numbers of actions that are running in a certain target.
-- return The numbers of actions that are running in a certain target.<br>
-- js NA
-- @function [parent=#ActionManager] getNumberOfRunningActionsInTarget
-- @param self
-- @param #cc.Node target
@ -110,7 +111,8 @@
--------------------------------
-- Removes all actions given its tag and the target.<br>
-- param tag The actions' tag.<br>
-- param target A certain target.
-- param target A certain target.<br>
-- js NA
-- @function [parent=#ActionManager] removeAllActionsByTag
-- @param self
-- @param #int tag

View File

@ -35,7 +35,8 @@
-- Make sure that the frames were previously loaded in the SpriteFrameCache.<br>
-- param dictionary An NSDictionary.<br>
-- param plist The path of the relative file,it use to find the plist path for load SpriteFrames.<br>
-- since v1.1
-- since v1.1<br>
-- js NA
-- @function [parent=#AnimationCache] addAnimationsWithDictionary
-- @param self
-- @param #map_table dictionary
@ -63,14 +64,15 @@
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Purges the cache. It releases all the Animation objects and the shared instance.
-- Purges the cache. It releases all the Animation objects and the shared instance.<br>
-- js NA
-- @function [parent=#AnimationCache] destroyInstance
-- @param self
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Returns the shared instance of the Animation cache. <br>
-- return The shared instance of the Animation cache.
-- Returns the shared instance of the Animation cache <br>
-- js NA
-- @function [parent=#AnimationCache] getInstance
-- @param self
-- @return AnimationCache#AnimationCache ret (return value: cc.AnimationCache)

View File

@ -43,7 +43,6 @@
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- js NA<br>
-- lua NA
-- @function [parent=#AtlasNode] getBlendFunc
-- @param self

View File

@ -24,7 +24,8 @@
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- Get the light type,light type MUST be one of LightType::DIRECTIONAL ,<br>
-- LightType::POINT, LightType::SPOT, LightType::AMBIENT.
-- @function [parent=#BaseLight] getLightType
-- @param self
-- @return int#int ret (return value: int)

View File

@ -124,13 +124,13 @@
-- @return Camera#Camera ret (return value: cc.Camera)
--------------------------------
--
-- Get the default camera of the current running scene.
-- @function [parent=#Camera] getDefaultCamera
-- @param self
-- @return Camera#Camera ret (return value: cc.Camera)
--------------------------------
--
-- Get the visiting camera , the visiting camera shall be set on Scene::render
-- @function [parent=#Camera] getVisitingCamera
-- @param self
-- @return Camera#Camera ret (return value: cc.Camera)

View File

@ -58,7 +58,7 @@
-- @return CardinalSplineTo#CardinalSplineTo self (return value: cc.CardinalSplineTo)
--------------------------------
-- js NA<br>
-- js ctor<br>
-- lua NA
-- @function [parent=#CardinalSplineTo] CardinalSplineTo
-- @param self

View File

@ -8,20 +8,25 @@
-- If stencil has no childre it will not be drawn.<br>
-- If you have custom stencil-based node with stencil drawing mechanics other then children-based,<br>
-- then this method should return true every time you wish stencil to be visited.<br>
-- By default returns true if has any children attached.<br>
-- return If you have custom stencil-based node with stencil drawing mechanics other then children-based,<br>
-- then this method should return true every time you wish stencil to be visited.<br>
-- By default returns true if has any children attached.
-- @function [parent=#ClippingNode] hasContent
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- Set the ClippingNode whether or not invert.<br>
-- param inverted A bool Type,to set the ClippingNode whether or not invert.
-- @function [parent=#ClippingNode] setInverted
-- @param self
-- @param #bool inverted
-- @return ClippingNode#ClippingNode self (return value: cc.ClippingNode)
--------------------------------
--
-- Set the Node to use as a stencil to do the clipping.<br>
-- param stencil The Node to use as a stencil to do the clipping.
-- @function [parent=#ClippingNode] setStencil
-- @param self
-- @param #cc.Node stencil
@ -31,7 +36,8 @@
-- The alpha threshold.<br>
-- The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.<br>
-- Should be a float between 0 and 1.<br>
-- This default to 1 (so alpha test is disabled).
-- This default to 1 (so alpha test is disabled).<br>
-- return The alpha threshold value,Should be a float between 0 and 1.
-- @function [parent=#ClippingNode] getAlphaThreshold
-- @param self
-- @return float#float ret (return value: float)
@ -39,13 +45,15 @@
--------------------------------
-- The Node to use as a stencil to do the clipping.<br>
-- The stencil node will be retained.<br>
-- This default to nil.
-- This default to nil.<br>
-- return The stencil node.
-- @function [parent=#ClippingNode] getStencil
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- Set the alpha threshold. <br>
-- param alphaThreshold The alpha threshold.
-- @function [parent=#ClippingNode] setAlphaThreshold
-- @param self
-- @param #float alphaThreshold
@ -54,7 +62,8 @@
--------------------------------
-- Inverted. If this is set to true,<br>
-- the stencil is inverted, so the content is drawn where the stencil is NOT drawn.<br>
-- This default to false.
-- This default to false.<br>
-- return If the clippingNode is Inverted, it will be return true.
-- @function [parent=#ClippingNode] isInverted
-- @param self
-- @return bool#bool ret (return value: bool)

View File

@ -5,26 +5,30 @@
-- @parent_module cc
--------------------------------
--
-- brief Get whether the clipping is enabled or not.<br>
-- return Whether the clipping is enabled or not. Default is true.
-- @function [parent=#ClippingRectangleNode] isClippingEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- brief Enable/Disable the clipping.<br>
-- param Pass true to enable clipping. Pass false to disable clipping.
-- @function [parent=#ClippingRectangleNode] setClippingEnabled
-- @param self
-- @param #bool enabled
-- @return ClippingRectangleNode#ClippingRectangleNode self (return value: cc.ClippingRectangleNode)
--------------------------------
--
-- brief Get the clipping rectangle.<br>
-- return The clipping rectangle.
-- @function [parent=#ClippingRectangleNode] getClippingRegion
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
--
-- brief Set the clipping rectangle.<br>
-- param Specify the clipping rectangle.
-- @function [parent=#ClippingRectangleNode] setClippingRegion
-- @param self
-- @param #rect_table clippingRegion

View File

@ -13,7 +13,8 @@
--------------------------------
-- Sets the EventDispatcher associated with this director.<br>
-- since v3.0
-- since v3.0<br>
-- js NA
-- @function [parent=#Director] setEventDispatcher
-- @param self
-- @param #cc.EventDispatcher dispatcher
@ -50,7 +51,8 @@
--------------------------------
-- Sets the OpenGL default values.<br>
-- It will enable alpha blending, disable depth test.
-- It will enable alpha blending, disable depth test.<br>
-- js NA
-- @function [parent=#Director] setGLDefaultValues
-- @param self
-- @return Director#Director self (return value: cc.Director)
@ -81,7 +83,8 @@
--------------------------------
-- Adds a matrix to the top of specified type of matrix stack.<br>
-- param type Matrix type.<br>
-- param mat The matrix that to be added.
-- param mat The matrix that to be added.<br>
-- js NA
-- @function [parent=#Director] loadMatrix
-- @param self
-- @param #int type
@ -104,7 +107,7 @@
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Gets singleton of TextureCache.
--
-- @function [parent=#Director] getTextureCache
-- @param self
-- @return TextureCache#TextureCache ret (return value: cc.TextureCache)
@ -138,7 +141,8 @@
-- @return Director#Director self (return value: cc.Director)
--------------------------------
-- Gets Frame Rate.
-- Gets Frame Rate.<br>
-- js NA
-- @function [parent=#Director] getFrameRate
-- @param self
-- @return float#float ret (return value: float)
@ -150,7 +154,8 @@
-- @return float#float ret (return value: float)
--------------------------------
-- Cleras all types of matrix stack, and add indentity matrix to these matrix stacks.
-- Cleras all types of matrix stack, and add indentity matrix to these matrix stacks.<br>
-- js NA
-- @function [parent=#Director] resetMatrixStack
-- @param self
-- @return Director#Director self (return value: cc.Director)
@ -164,7 +169,8 @@
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
-- Clones a specified type matrix and put it to the top of specified type of matrix stack.
-- Clones a specified type matrix and put it to the top of specified type of matrix stack.<br>
-- js NA
-- @function [parent=#Director] pushMatrix
-- @param self
-- @param #int type
@ -191,7 +197,8 @@
-- @return Director#Director self (return value: cc.Director)
--------------------------------
-- Gets the top matrix of specified type of matrix stack.
-- Gets the top matrix of specified type of matrix stack.<br>
-- js NA
-- @function [parent=#Director] getMatrix
-- @param self
-- @param #int type
@ -207,7 +214,6 @@
--------------------------------
-- Get the GLView.<br>
-- js NA<br>
-- lua NA
-- @function [parent=#Director] getOpenGLView
-- @param self
@ -257,7 +263,9 @@
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets clear values for the color buffers, value range of each element is [0.0, 1.0].
-- Sets clear values for the color buffers,<br>
-- value range of each element is [0.0, 1.0].<br>
-- js NA
-- @function [parent=#Director] setClearColor
-- @param self
-- @param #color4f_table clearColor
@ -272,8 +280,7 @@
--------------------------------
-- Sets the GLView. <br>
-- lua NA<br>
-- js NA
-- lua NA
-- @function [parent=#Director] setOpenGLView
-- @param self
-- @param #cc.GLView openGLView
@ -305,7 +312,8 @@
-- Enters the Director's main loop with the given Scene.<br>
-- Call it to run only your FIRST scene.<br>
-- Don't call it if there is already a running scene.<br>
-- It will call pushScene: and then it will call startAnimation
-- It will call pushScene: and then it will call startAnimation<br>
-- js NA
-- @function [parent=#Director] runWithScene
-- @param self
-- @param #cc.Scene scene
@ -327,7 +335,7 @@
-- @return Director#Director self (return value: cc.Director)
--------------------------------
-- Restart the director.
--
-- @function [parent=#Director] restart
-- @param self
-- @return Director#Director self (return value: cc.Director)
@ -342,7 +350,8 @@
-- @return Director#Director self (return value: cc.Director)
--------------------------------
-- Adds an identity matrix to the top of specified type of matrxi stack.
-- Adds an identity matrix to the top of specified type of matrxi stack.<br>
-- js NA
-- @function [parent=#Director] loadIdentityMatrix
-- @param self
-- @param #int type
@ -363,7 +372,8 @@
--------------------------------
-- Returns the Console associated with this director.<br>
-- since v3.0
-- since v3.0<br>
-- js NA
-- @function [parent=#Director] getConsole
-- @param self
-- @return Console#Console ret (return value: cc.Console)
@ -371,7 +381,8 @@
--------------------------------
-- Multipies a matrix to the top of specified type of matrix stack.<br>
-- param type Matrix type.<br>
-- param mat The matrix that to be multipied.
-- param mat The matrix that to be multipied.<br>
-- js NA
-- @function [parent=#Director] multiplyMatrix
-- @param self
-- @param #int type
@ -395,7 +406,8 @@
-- @return Director#Director self (return value: cc.Director)
--------------------------------
-- Pops the top matrix of the specified type of matrix stack.
-- Pops the top matrix of the specified type of matrix stack.<br>
-- js NA
-- @function [parent=#Director] popMatrix
-- @param self
-- @param #int type
@ -446,14 +458,16 @@
--------------------------------
-- Gets the EventDispatcher associated with this director.<br>
-- since v3.0
-- since v3.0<br>
-- js NA
-- @function [parent=#Director] getEventDispatcher
-- @param self
-- @return EventDispatcher#EventDispatcher ret (return value: cc.EventDispatcher)
--------------------------------
-- Replaces the running scene with a new one. The running scene is terminated.<br>
-- ONLY call it if there is a running scene.
-- ONLY call it if there is a running scene.<br>
-- js NA
-- @function [parent=#Director] replaceScene
-- @param self
-- @param #cc.Scene scene
@ -474,7 +488,8 @@
-- @return ActionManager#ActionManager ret (return value: cc.ActionManager)
--------------------------------
-- Returns a shared instance of the director.
-- Returns a shared instance of the director. <br>
-- js _getInstance
-- @function [parent=#Director] getInstance
-- @param self
-- @return Director#Director ret (return value: cc.Director)

Some files were not shown because too many files have changed in this diff Show More