closed #2050: Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into bug2050_tilemap_firstgid_bug

Conflicts:
	cocos/2d/CCTMXLayer.cpp
This commit is contained in:
boyu0 2013-12-23 15:40:33 +08:00
commit 0cbbfdba8c
206 changed files with 6918 additions and 3337 deletions

View File

@ -669,6 +669,15 @@ Developers:
zhiqiangxu
Fixed a logic error in ControlUtils::RectUnion.
yinkaile (2youyouo2)
Maintainer of Armature Bone Animation.
dmurtagh
Fixed a bug that UserDefault::getDoubleForKey() doesn't pass default value to Java.
seobyeongky
Updates spine runtime.
Retired Core Developers:
WenSheng Yang
Author of windows port, CCTextField,

View File

@ -4,11 +4,19 @@ cocos2d-x-3.0beta0 ?? 2013
[NEW] SChedule::performFunctionInCocosThread()
[NEW] Added tga format support again.
[FIX] A Logic error in ControlUtils::RectUnion.
[FIX] Bug fixes for Armature, use Vector<T>, Map<K, V> instead of Array, Dictionary.
[FIX] Used c++11 range loop(highest performance) instead of other types of loop.
[FIX] Removed most hungarian notations.
[FIX] Merged NodeRGBA to Node.
[NEW] New renderer support.
[FIX] Potential hash collision fix.
[FIX] Updates spine runtime to the latest version.
[Android]
[NEW] build/android-build.sh: add supporting to generate .apk file
[FIX] XMLHttpRequest receives wrong binary array.
[NEW] Bindings-generator supports to bind 'unsigned long'.
[FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes.
[FIX] UserDefault::getDoubleForKey() doesn't pass default value to Java.
[Windows]
[NEW] CMake support for windows.

View File

@ -12,18 +12,6 @@ LUA_SAMPLES = ['hellolua', 'testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def usage():
print """%s [-n ndk-build-parameter] [-p android-platform] [-b build-mode] target.
Valid android-platform are:[10|11|12|13|14|15|16|17]
Valid build-mode are:[debug|release]
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon
|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" % sys.argv[0]
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
@ -253,14 +241,23 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
if __name__ == '__main__':
#parse the params
parser = OptionParser()
parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform", help='parameter for android-update')
parser.add_option("-b", "--build", dest="build_mode", help='the build mode for java project,debug or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
usage = """usage: %prog [options] target
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely."""
parser = OptionParser(usage=usage)
parser.add_option("-n", "--ndk", dest="ndk_build_param",
help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
(opts, args) = parser.parse_args()
if len(args) == 0:
usage()
parser.print_help()
else:
try:
build_samples(args, opts.ndk_build_param,opts.android_platform,opts.build_mode)

View File

@ -1 +1 @@
4cd02813dfcd14b7de3ccb157cd0f25b0bce9f37
1df2ba5492ecdbe0c160d2429733c1371b35b21a

View File

@ -24,7 +24,6 @@ CCActionTween.cpp \
CCAnimation.cpp \
CCAnimationCache.cpp \
CCAtlasNode.cpp \
CCCamera.cpp \
ccCArray.cpp \
CCClippingNode.cpp \
CCComponent.cpp \
@ -60,6 +59,7 @@ CCGLProgram.cpp \
ccGLStateCache.cpp \
CCGrabber.cpp \
CCGrid.cpp \
CCNodeGrid.cpp \
CCIMEDispatcher.cpp \
CCLabel.cpp \
CCLabelAtlas.cpp \

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
@ -26,7 +26,6 @@ THE SOFTWARE.
#include "CCActionCamera.h"
#include "CCNode.h"
#include "CCCamera.h"
#include "CCStdC.h"
NS_CC_BEGIN
@ -36,11 +35,6 @@ NS_CC_BEGIN
void ActionCamera::startWithTarget(Node *target)
{
ActionInterval::startWithTarget(target);
Camera *camera = target->getCamera();
camera->getCenter(&_centerXOrig, &_centerYOrig, &_centerZOrig);
camera->getEye(&_eyeXOrig, &_eyeYOrig, &_eyeZOrig);
camera->getUp(&_upXOrig, &_upYOrig, &_upZOrig);
}
ActionCamera* ActionCamera::clone() const
@ -56,6 +50,88 @@ ActionCamera * ActionCamera::reverse() const
// FIXME: This conversion isn't safe.
return (ActionCamera*)ReverseTime::create(const_cast<ActionCamera*>(this));
}
void ActionCamera::restore()
{
_eyeX = _eyeY = 0.0f;
_eyeZ = FLT_EPSILON;
_centerX = _centerY = _centerZ = 0.0f;
_upX = 0.0f;
_upY = 1.0f;
_upZ = 0.0f;
}
void ActionCamera::setEye(float x, float y, float z)
{
_eyeX = x;
_eyeY = y;
_eyeZ = z;
updateTransform();
}
void ActionCamera::setCenter(float centerX, float centerY, float centerZ)
{
_centerX = centerX;
_centerY = centerY;
_centerZ = centerZ;
updateTransform();
}
void ActionCamera::setUp(float upX, float upY, float upZ)
{
_upX = upX;
_upY = upY;
_upZ = upZ;
updateTransform();
}
void ActionCamera::updateTransform()
{
kmVec3 eye, center, up;
kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ);
kmVec3Fill(&center, _centerX, _centerY, _centerZ);
kmVec3Fill(&up, _upX, _upY, _upZ);
kmMat4 lookupMatrix;
kmMat4LookAt(&lookupMatrix, &eye, &center, &up);
Point anchorPoint = _target->getAnchorPointInPoints();
bool needsTranslation = !anchorPoint.equals(Point::ZERO);
kmMat4 mv;
kmMat4Identity(&mv);
if(needsTranslation) {
kmMat4 t;
kmMat4Translation(&t, anchorPoint.x, anchorPoint.y, 0);
kmMat4Multiply(&mv, &mv, &t);
}
kmMat4Multiply(&mv, &mv, &lookupMatrix);
if(needsTranslation) {
kmMat4 t;
kmMat4Translation(&t, -anchorPoint.x, -anchorPoint.y, 0);
kmMat4Multiply(&mv, &mv, &t);
}
// XXX FIXME TODO
// Using the AdditionalTransform is a complete hack.
// This should be done by multipliying the lookup-Matrix with the Node's MV matrix
// And then setting the result as the new MV matrix
// But that operation needs to be done after all the 'updates'.
// So the Director should emit an 'director_after_update' event.
// And this object should listen to it
_target->setAdditionalTransform(mv);
}
//
// OrbitCamera
//
@ -101,7 +177,8 @@ bool OrbitCamera::initWithDuration(float t, float radius, float deltaRadius, flo
void OrbitCamera::startWithTarget(Node *target)
{
ActionInterval::startWithTarget(target);
ActionCamera::startWithTarget(target);
float r, zenith, azimuth;
this->sphericalRadius(&r, &zenith, &azimuth);
if( isnan(_radius) )
@ -117,30 +194,25 @@ void OrbitCamera::startWithTarget(Node *target)
void OrbitCamera::update(float dt)
{
float r = (_radius + _deltaRadius * dt) * Camera::getZEye();
float r = (_radius + _deltaRadius * dt) * FLT_EPSILON;
float za = _radZ + _radDeltaZ * dt;
float xa = _radX + _radDeltaX * dt;
float i = sinf(za) * cosf(xa) * r + _centerXOrig;
float j = sinf(za) * sinf(xa) * r + _centerYOrig;
float k = cosf(za) * r + _centerZOrig;
float i = sinf(za) * cosf(xa) * r + _centerX;
float j = sinf(za) * sinf(xa) * r + _centerY;
float k = cosf(za) * r + _centerZ;
_target->getCamera()->setEye(i,j,k);
setEye(i,j,k);
}
void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimuth)
{
float ex, ey, ez, cx, cy, cz, x, y, z;
float r; // radius
float s;
Camera* camera = _target->getCamera();
camera->getEye(&ex, &ey, &ez);
camera->getCenter(&cx, &cy, &cz);
x = ex-cx;
y = ey-cy;
z = ez-cz;
float x = _eyeX - _centerX;
float y = _eyeY - _centerY;
float z = _eyeZ - _centerZ;
r = sqrtf( powf(x,2) + powf(y,2) + powf(z,2));
s = sqrtf( powf(x,2) + powf(y,2));
@ -155,7 +227,7 @@ void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimut
else
*azimuth = asinf(y/s);
*newRadius = r / Camera::getZEye();
*newRadius = r / FLT_EPSILON;
}
NS_CC_END

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#define __CCCAMERA_ACTION_H__
#include "CCActionInterval.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN
@ -48,15 +49,15 @@ public:
* @js ctor
*/
ActionCamera()
:_centerXOrig(0)
,_centerYOrig(0)
,_centerZOrig(0)
,_eyeXOrig(0)
,_eyeYOrig(0)
,_eyeZOrig(0)
,_upXOrig(0)
,_upYOrig(0)
,_upZOrig(0)
:_centerX(0)
,_centerY(0)
,_centerZ(0)
,_eyeX(0)
,_eyeY(0)
,_eyeZ(FLT_EPSILON)
,_upX(0)
,_upY(1)
,_upZ(0)
{}
/**
* @js NA
@ -70,17 +71,22 @@ public:
virtual ActionCamera *clone() const override;
protected:
float _centerXOrig;
float _centerYOrig;
float _centerZOrig;
float _eyeXOrig;
float _eyeYOrig;
float _eyeZOrig;
void restore();
void setEye(float x, float y, float z);
void setCenter(float x, float y, float z);
void setUp(float x, float y, float z);
void updateTransform();
float _upXOrig;
float _upYOrig;
float _upZOrig;
float _centerX;
float _centerY;
float _centerZ;
float _eyeX;
float _eyeY;
float _eyeZ;
float _upX;
float _upY;
float _upZ;
};
/**
@ -112,7 +118,7 @@ public:
* @js NA
* @lua NA
*/
~OrbitCamera(){}
virtual ~OrbitCamera(){}
/** initializes a OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */
bool initWithDuration(float t, float radius, float deltaRadius, float angleZ, float deltaAngleZ, float angleX, float deltaAngleX);

View File

@ -25,6 +25,7 @@ THE SOFTWARE.
#include "CCActionGrid.h"
#include "CCDirector.h"
#include "CCGrid.h"
#include "CCNodeGrid.h"
NS_CC_BEGIN
// implementation of GridAction
@ -44,11 +45,11 @@ bool GridAction::initWithDuration(float duration, const Size& gridSize)
void GridAction::startWithTarget(Node *target)
{
ActionInterval::startWithTarget(target);
cacheTargetAsGridNode();
GridBase *newgrid = this->getGrid();
Node *t = _target;
GridBase *targetGrid = t->getGrid();
GridBase *targetGrid = _gridNodeTarget->getGrid();
if (targetGrid && targetGrid->getReuseGrid() > 0)
{
@ -69,11 +70,17 @@ void GridAction::startWithTarget(Node *target)
targetGrid->setActive(false);
}
t->setGrid(newgrid);
t->getGrid()->setActive(true);
_gridNodeTarget->setGrid(newgrid);
_gridNodeTarget->getGrid()->setActive(true);
}
}
void GridAction::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
GridAction* GridAction::reverse() const
{
// FIXME: This conversion isn't safe.
@ -97,19 +104,19 @@ GridBase* Grid3DAction::getGrid()
Vertex3F Grid3DAction::getVertex(const Point& position) const
{
Grid3D *g = (Grid3D*)_target->getGrid();
Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getVertex(position);
}
Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const
{
Grid3D *g = (Grid3D*)_target->getGrid();
Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getOriginalVertex(position);
}
void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex)
{
Grid3D *g = (Grid3D*)_target->getGrid();
Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
g->setVertex(position, vertex);
}
@ -122,19 +129,19 @@ GridBase* TiledGrid3DAction::getGrid(void)
Quad3 TiledGrid3DAction::getTile(const Point& pos) const
{
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid();
TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getTile(pos);
}
Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const
{
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid();
TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getOriginalTile(pos);
}
void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords)
{
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid();
TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->setTile(pos, coords);
}
@ -345,14 +352,20 @@ DeccelAmplitude* DeccelAmplitude::reverse() const
void StopGrid::startWithTarget(Node *target)
{
ActionInstant::startWithTarget(target);
GridBase *grid = _target->getGrid();
cacheTargetAsGridNode();
GridBase *grid = _gridNodeTarget->getGrid();
if (grid && grid->isActive())
{
grid->setActive(false);
}
}
void StopGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
StopGrid* StopGrid::create()
{
StopGrid* pAction = new StopGrid();
@ -402,13 +415,20 @@ bool ReuseGrid::initWithTimes(int times)
void ReuseGrid::startWithTarget(Node *target)
{
ActionInstant::startWithTarget(target);
cacheTargetAsGridNode();
if (_target->getGrid() && _target->getGrid()->isActive())
if (_gridNodeTarget->getGrid() && _gridNodeTarget->getGrid()->isActive())
{
_target->getGrid()->setReuseGrid(_target->getGrid()->getReuseGrid() + _times);
_gridNodeTarget->getGrid()->setReuseGrid(_gridNodeTarget->getGrid()->getReuseGrid() + _times);
}
}
void ReuseGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
ReuseGrid* ReuseGrid::clone() const
{
return ReuseGrid::create(_times);

View File

@ -31,6 +31,7 @@ THE SOFTWARE.
NS_CC_BEGIN
class GridBase;
class NodeGrid;
/**
* @addtogroup actions
@ -57,6 +58,10 @@ protected:
bool initWithDuration(float duration, const Size& gridSize);
Size _gridSize;
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private:
CC_DISALLOW_COPY_AND_ASSIGN(GridAction);
@ -264,6 +269,10 @@ public:
protected:
StopGrid() {}
virtual ~StopGrid() {}
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private:
CC_DISALLOW_COPY_AND_ASSIGN(StopGrid);
@ -286,7 +295,11 @@ protected:
virtual ~ReuseGrid() {}
/** initializes an action with the number of times that the current grid will be reused */
bool initWithTimes(int times);
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
int _times;
private:

View File

@ -158,9 +158,9 @@ Vector<Node*> ActionManager::pauseAllRunningActions()
void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume)
{
std::for_each(targetsToResume.begin(), targetsToResume.end(), [this](Node* node){
for(const auto &node : targetsToResume) {
this->resumeTarget(node);
});
}
}
// run

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#include "CCDirector.h"
#include "ccMacros.h"
#include "CCGrid.h"
#include "CCNodeGrid.h"
#include <stdlib.h>
NS_CC_BEGIN
@ -279,7 +280,7 @@ void ShuffleTiles::placeTile(const Point& pos, Tile *t)
{
Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep();
Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (int)(t->position.x * step.x);
coords.bl.y += (int)(t->position.y * step.y);
@ -408,7 +409,7 @@ void FadeOutTRTiles::turnOffTile(const Point& pos)
void FadeOutTRTiles::transformTile(const Point& pos, float distance)
{
Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep();
Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (step.x / 2) * (1.0f - distance);
coords.bl.y += (step.y / 2) * (1.0f - distance);
@ -535,7 +536,7 @@ float FadeOutUpTiles::testFunc(const Size& pos, float time)
void FadeOutUpTiles::transformTile(const Point& pos, float distance)
{
Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep();
Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.y += (step.y / 2) * (1.0f - distance);
coords.br.y += (step.y / 2) * (1.0f - distance);

View File

@ -203,9 +203,9 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary)
version = properties.at("format").asInt();
const ValueVector& spritesheets = properties.at("spritesheets").asValueVector();
std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){
for(const auto &value : spritesheets) {
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString());
});
}
}
switch (version) {

View File

@ -1,144 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCCamera.h"
#include "CCString.h"
#include "CCGL.h"
#include "CCDrawingPrimitives.h"
#include "CCDirector.h"
#include "kazmath/GL/matrix.h"
using namespace std;
NS_CC_BEGIN
Camera::Camera(void)
{
init();
}
Camera::~Camera(void)
{
}
std::string Camera::getDescription() const
{
return String::createWithFormat("<Camera | center = (%.2f,%.2f,%.2f)>", _centerX, _centerY, _centerZ)->getCString();
}
void Camera::init(void)
{
restore();
}
void Camera::restore(void)
{
_eyeX = _eyeY = 0.0f;
_eyeZ = getZEye();
_centerX = _centerY = _centerZ = 0.0f;
_upX = 0.0f;
_upY = 1.0f;
_upZ = 0.0f;
kmMat4Identity(&_lookupMatrix);
_dirty = false;
}
void Camera::locate(void)
{
if (_dirty)
{
kmVec3 eye, center, up;
kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ);
kmVec3Fill(&center, _centerX, _centerY, _centerZ);
kmVec3Fill(&up, _upX, _upY, _upZ);
kmMat4LookAt(&_lookupMatrix, &eye, &center, &up);
_dirty = false;
}
kmGLMultMatrix(&_lookupMatrix);
}
float Camera::getZEye(void)
{
return FLT_EPSILON;
}
void Camera::setEye(float eyeX, float eyeY, float eyeZ)
{
_eyeX = eyeX;
_eyeY = eyeY;
_eyeZ = eyeZ;
_dirty = true;
}
void Camera::setCenter(float centerX, float centerY, float centerZ)
{
_centerX = centerX;
_centerY = centerY;
_centerZ = centerZ;
_dirty = true;
}
void Camera::setUp(float upX, float upY, float upZ)
{
_upX = upX;
_upY = upY;
_upZ = upZ;
_dirty = true;
}
void Camera::getEye(float *eyeX, float *eyeY, float *eyeZ) const
{
*eyeX = _eyeX;
*eyeY = _eyeY;
*eyeZ = _eyeZ;
}
void Camera::getCenter(float *centerX, float *centerY, float *centerZ) const
{
*centerX = _centerX;
*centerY = _centerY;
*centerZ = _centerZ;
}
void Camera::getUp(float *upX, float *upY, float *upZ) const
{
*upX = _upX;
*upY = _upY;
*upZ = _upZ;
}
NS_CC_END

View File

@ -1,186 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __COCOS2DX_CAMERA_H__
#define __COCOS2DX_CAMERA_H__
#include <string>
#include "CCObject.h"
#include "ccMacros.h"
#include "kazmath/mat4.h"
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
/**
A Camera is used in every Node.
Useful to look at the object from different views.
The OpenGL gluLookAt() function is used to locate the
camera.
If the object is transformed by any of the scale, rotation or
position attributes, then they will override the camera.
IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both.
World coordinates won't work if you use the camera.
Limitations:
- Some nodes, like ParallaxNode, Particle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors)
using the camera.
- It doesn't work on batched nodes like Sprite objects when they are parented to a SpriteBatchNode object.
- It is recommended to use it ONLY if you are going to create 3D effects. For 2D effects, use the action Follow or position/scale/rotate.
*/
class CC_DLL Camera : public Object
{
public:
/** returns the Z eye */
static float getZEye();
/**
* @js ctor
*/
Camera();
/**
* @js NA
* @lua NA
*/
~Camera();
void init();
/**
* @js NA
* @lua NA
*/
virtual std::string getDescription() const;
/** sets the dirty value */
inline void setDirty(bool value) { _dirty = value; }
/** get the dirty value */
inline bool isDirty() const { return _dirty; }
/** sets the camera in the default position */
void restore();
/** Sets the camera using gluLookAt using its eye, center and up_vector */
void locate();
/** sets the eye values in points */
void setEye(float eyeX, float eyeY, float eyeZ);
/**
@deprecated. Use setEye() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setEyeXYZ(float eyeX, float eyeY, float eyeZ){ setEye(eyeX, eyeY, eyeZ);}
/** sets the center values in points */
void setCenter(float centerX, float centerY, float centerZ);
/**
@deprecated. Use setCenter() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setCenterXYZ(float centerX, float centerY, float centerZ){ setCenter(centerX,centerY,centerZ);}
/** sets the up values */
void setUp(float upX, float upY, float upZ);
/**
@deprecated. Use setUp() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setUpXYZ(float upX, float upY, float upZ){ setUp(upX,upY,upZ); }
/** get the eye vector values in points
* @code
* when this function bound to js or lua,the input params are changed
* in js: var getEye()
* in lua:local getEye()
* @endcode
*/
void getEye(float *eyeX, float *eyeY, float *eyeZ) const;
/**
@deprecated. Use getEye() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getEyeXYZ(float *eyeX, float *eyeY, float *eyeZ) const { getEye(eyeX, eyeY, eyeZ); }
/** get the center vector values int points
* when this function bound to js or lua,the input params are changed
* in js: var getCenter()
* in lua:local getCenter()
*/
void getCenter(float *centerX, float *centerY, float *centerZ) const;
/**
@deprecated. Use getCenter() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getCenterXYZ(float *centerX, float *centerY, float *centerZ) const{ getCenter(centerX,centerY,centerZ); }
/** get the up vector values
* when this function bound to js or lua,the input params are changed
* in js: var getUp()
* in lua:local getUp()
*/
void getUp(float *upX, float *upY, float *upZ) const;
/**
@deprecated. Use getUp() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getUpXYZ(float *upX, float *upY, float *upZ) const{ getUp(upX, upY, upZ); }
protected:
float _eyeX;
float _eyeY;
float _eyeZ;
float _centerX;
float _centerY;
float _centerZ;
float _upX;
float _upY;
float _upZ;
bool _dirty;
kmMat4 _lookupMatrix;
private:
DISALLOW_COPY_AND_ASSIGN(Camera);
};
// end of base_node group
/// @}
NS_CC_END
#endif // __COCOS2DX_CAMERA_H__

View File

@ -41,9 +41,9 @@ static void setProgram(Node *n, GLProgram *p)
n->setShaderProgram(p);
auto& children = n->getChildren();
std::for_each(children.begin(), children.end(), [p](Node* child){
for(const auto &child : children) {
setProgram(child, p);
});
}
}
ClippingNode::ClippingNode()

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#define __CC_FRAMEWORK_COMCONTAINER_H__
#include "CCMap.h"
#include <string>
NS_CC_BEGIN

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
@ -48,7 +48,6 @@ THE SOFTWARE.
#include "CCActionManager.h"
#include "CCAnimationCache.h"
#include "CCTouch.h"
#include "CCEventDispatcher.h"
#include "CCUserDefault.h"
#include "ccGLStateCache.h"
#include "CCShaderCache.h"
@ -59,6 +58,7 @@ THE SOFTWARE.
#include "CCEGLView.h"
#include "CCConfiguration.h"
#include "CCEventDispatcher.h"
#include "CCEventCustom.h"
#include "CCFontFreeType.h"
#include "CCRenderer.h"
#include "renderer/CCFrustum.h"
@ -84,6 +84,11 @@ static DisplayLinkDirector *s_SharedDirector = nullptr;
#define kDefaultFPS 60 // 60 frames per second
extern const char* cocos2dVersion(void);
const char *Director::EVENT_PROJECTION_CHANGED = "director_projection_changed";
const char *Director::EVENT_AFTER_DRAW = "director_after_draw";
const char *Director::EVENT_AFTER_VISIT = "director_after_visit";
const char *Director::EVENT_AFTER_UPDATE = "director_after_udpate";
Director* Director::getInstance()
{
if (!s_SharedDirector)
@ -95,9 +100,8 @@ Director* Director::getInstance()
return s_SharedDirector;
}
Director::Director(void)
Director::Director()
{
}
bool Director::init(void)
@ -146,6 +150,16 @@ bool Director::init(void)
_scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
_eventDispatcher = new EventDispatcher();
_eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW);
_eventAfterDraw->setUserData(this);
_eventAfterVisit = new EventCustom(EVENT_AFTER_VISIT);
_eventAfterVisit->setUserData(this);
_eventAfterUpdate = new EventCustom(EVENT_AFTER_UPDATE);
_eventAfterUpdate->setUserData(this);
_eventProjectionChanged = new EventCustom(EVENT_PROJECTION_CHANGED);
_eventProjectionChanged->setUserData(this);
//init TextureCache
initTextureCache();
@ -172,6 +186,11 @@ Director::~Director(void)
CC_SAFE_RELEASE(_actionManager);
CC_SAFE_RELEASE(_eventDispatcher);
delete _eventAfterUpdate;
delete _eventAfterDraw;
delete _eventAfterVisit;
delete _eventProjectionChanged;
delete _renderer;
// pop the autorelease pool
@ -252,6 +271,7 @@ void Director::drawScene()
if (! _paused)
{
_scheduler->update(_deltaTime);
_eventDispatcher->dispatchEvent(_eventAfterUpdate);
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@ -279,6 +299,7 @@ void Director::drawScene()
if (_runningScene)
{
_runningScene->visit();
_eventDispatcher->dispatchEvent(_eventAfterVisit);
}
// draw the notifications node
@ -293,6 +314,7 @@ void Director::drawScene()
}
_renderer->render();
_eventDispatcher->dispatchEvent(_eventAfterDraw);
kmGLPopMatrix();
@ -473,6 +495,8 @@ void Director::setProjection(Projection projection)
_projection = projection;
GL::setProjectionMatrixDirty();
_eventDispatcher->dispatchEvent(_eventProjectionChanged);
}
void Director::purgeCachedData(void)

View File

@ -54,6 +54,8 @@ class Node;
class Scheduler;
class ActionManager;
class EventDispatcher;
class EventCustom;
class EventListenerCustom;
class TextureCache;
class Frustum;
class Renderer;
@ -81,6 +83,12 @@ and when to execute the Scenes.
class CC_DLL Director : public Object
{
public:
static const char *EVENT_PROJECTION_CHANGED;
static const char* EVENT_AFTER_UPDATE;
static const char* EVENT_AFTER_VISIT;
static const char* EVENT_AFTER_DRAW;
/** @typedef ccDirectorProjection
Possible OpenGL projections used by director
*/
@ -414,6 +422,7 @@ protected:
@since v3.0
*/
EventDispatcher* _eventDispatcher;
EventCustom *_eventProjectionChanged, *_eventAfterDraw, *_eventAfterVisit, *_eventAfterUpdate;
/* delta time since last tick to main loop */
float _deltaTime;

View File

@ -29,6 +29,7 @@
#include <string>
#include <stdint.h>
#include "CCObject.h"
#include "CCPlatformMacros.h"
NS_CC_BEGIN
@ -38,7 +39,7 @@ class Node;
/**
* Base class of all kinds of events.
*/
class Event
class Event : public Object
{
public:
enum class Type

View File

@ -26,6 +26,11 @@
#include "CCEventTouch.h"
#include "CCEventCustom.h"
#include "CCEventListenerTouch.h"
#include "CCEventListenerAcceleration.h"
#include "CCEventListenerMouse.h"
#include "CCEventListenerKeyboard.h"
#include "CCEventListenerCustom.h"
#include "CCNode.h"
#include "CCDirector.h"
@ -59,31 +64,30 @@ private:
NS_CC_BEGIN
static EventListener::ListenerID getListenerID(Event* event)
static EventListener::ListenerID __getListenerID(Event* event)
{
EventListener::ListenerID ret;
switch (event->getType())
{
case Event::Type::ACCELERATION:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::ACCELERATION);
ret = EventListenerAcceleration::LISTENER_ID;
break;
case Event::Type::CUSTOM:
{
auto customEvent = static_cast<EventCustom*>(event);
auto listenerID = std::hash<std::string>()(customEvent->getEventName());
ret = static_cast<EventListener::ListenerID>(listenerID);
ret = customEvent->getEventName();
}
break;
case Event::Type::KEYBOARD:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::KEYBOARD);
ret = EventListenerKeyboard::LISTENER_ID;
break;
case Event::Type::MOUSE:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::MOUSE);
ret = EventListenerMouse::LISTENER_ID;
break;
case Event::Type::TOUCH:
// Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce.
// return UNKNOW instead.
ret = static_cast<EventListener::ListenerID>(EventListener::Type::UNKNOWN);
// return UNKNOWN instead.
CCASSERT(false, "Don't call this method if the event is for touch.");
break;
default:
CCASSERT(false, "Invalid type!");
@ -335,6 +339,8 @@ void EventDispatcher::addEventListener(EventListener* listener)
{
_toAddedListeners.push_back(listener);
}
listener->retain();
}
void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)
@ -349,7 +355,6 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list
listener->setFixedPriority(0);
listener->setRegistered(true);
listener->retain();
addEventListener(listener);
associateNodeAndEventListener(node, listener);
@ -373,12 +378,17 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener,
listener->setFixedPriority(fixedPriority);
listener->setRegistered(true);
listener->setPaused(false);
listener->retain();
addEventListener(listener);
}
EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, std::function<void(EventCustom*)> callback)
{
EventListenerCustom *listener = EventListenerCustom::create(eventName, callback);
addEventListenerWithFixedPriority(listener, 1);
return listener;
}
void EventDispatcher::removeEventListener(EventListener* listener)
{
if (listener == nullptr)
@ -557,7 +567,7 @@ void EventDispatcher::dispatchEvent(Event* event)
return;
}
auto listenerID = getListenerID(event);
auto listenerID = __getListenerID(event);
sortEventListeners(listenerID);
@ -578,16 +588,21 @@ void EventDispatcher::dispatchEvent(Event* event)
updateListeners(event);
}
void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData)
{
EventCustom ev(eventName);
ev.setUserData(optionalUserData);
dispatchEvent(&ev);
}
void EventDispatcher::dispatchTouchEvent(EventTouch* event)
{
auto touchOneByOneID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE);
auto touchAllAtOnceID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE);
sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID);
sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
sortEventListeners(touchOneByOneID);
sortEventListeners(touchAllAtOnceID);
auto oneByOnelisteners = getListeners(touchOneByOneID);
auto allAtOncelisteners = getListeners(touchAllAtOnceID);
auto oneByOnelisteners = getListeners(EventListenerTouchOneByOne::LISTENER_ID);
auto allAtOncelisteners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
// If there aren't any touch listeners, return directly.
if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners)
@ -776,7 +791,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
void EventDispatcher::updateListeners(Event* event)
{
auto onUpdateListeners = [this](EventListener::ListenerID listenerID)
auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID)
{
auto listenersIter = _listeners.find(listenerID);
if (listenersIter == _listeners.end())
@ -844,12 +859,12 @@ void EventDispatcher::updateListeners(Event* event)
if (event->getType() == Event::Type::TOUCH)
{
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE));
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE));
onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID);
onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
}
else
{
onUpdateListeners(getListenerID(event));
onUpdateListeners(__getListenerID(event));
}
@ -907,7 +922,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph()
}
}
void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID)
void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID)
{
DirtyFlag dirtyFlag = DirtyFlag::NONE;
@ -933,7 +948,7 @@ void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID)
}
}
void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID)
void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID)
{
auto listeners = getListeners(listenerID);
@ -962,7 +977,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::List
#endif
}
void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID)
void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID)
{
auto listeners = getListeners(listenerID);
@ -996,7 +1011,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerI
}
EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::ListenerID listenerID)
EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID)
{
auto iter = _listeners.find(listenerID);
if (iter != _listeners.end())
@ -1007,7 +1022,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene
return nullptr;
}
void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerID listenerID)
void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID)
{
auto listenerItemIter = _listeners.find(listenerID);
if (listenerItemIter != _listeners.end())
@ -1068,26 +1083,47 @@ void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerI
void EventDispatcher::removeEventListeners(EventListener::Type listenerType)
{
CCASSERT(listenerType != EventListener::Type::CUSTOM, "Not support custom event listener type, please use EventDispatcher::removeCustomEventListeners instead.");
removeEventListenersForListenerID(static_cast<EventListener::ListenerID>(listenerType));
if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE)
{
removeEventListenersForListenerID(EventListenerTouchOneByOne::LISTENER_ID);
}
else if (listenerType == EventListener::Type::TOUCH_ALL_AT_ONCE)
{
removeEventListenersForListenerID(EventListenerTouchAllAtOnce::LISTENER_ID);
}
else if (listenerType == EventListener::Type::MOUSE)
{
removeEventListenersForListenerID(EventListenerMouse::LISTENER_ID);
}
else if (listenerType == EventListener::Type::ACCELERATION)
{
removeEventListenersForListenerID(EventListenerAcceleration::LISTENER_ID);
}
else if (listenerType == EventListener::Type::KEYBOARD)
{
removeEventListenersForListenerID(EventListenerKeyboard::LISTENER_ID);
}
else
{
CCASSERT(false, "Invalid listener type!");
}
}
void EventDispatcher::removeCustomEventListeners(const std::string& customEventName)
{
removeEventListenersForListenerID(std::hash<std::string>()(customEventName));
removeEventListenersForListenerID(customEventName);
}
void EventDispatcher::removeAllEventListeners()
{
std::vector<EventListener::ListenerID> types(_listeners.size());
for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter)
for (const auto& e : _listeners)
{
types.push_back(iter->first);
types.push_back(e.first);
}
for (auto& type : types)
for (const auto& type : types)
{
removeEventListenersForListenerID(type);
}
@ -1118,7 +1154,7 @@ void EventDispatcher::setDirtyForNode(Node* node)
}
}
void EventDispatcher::setDirty(EventListener::ListenerID listenerID, DirtyFlag flag)
void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag)
{
auto iter = _priorityDirtyFlagMap.find(listenerID);
if (iter == _priorityDirtyFlagMap.end())

View File

@ -40,6 +40,8 @@ NS_CC_BEGIN
class Event;
class EventTouch;
class Node;
class EventCustom;
class EventListenerCustom;
/**
This class manages event listener subscriptions
@ -69,17 +71,23 @@ public:
*/
void addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority);
/** Remove a listener
/** Adds a Custom event listener.
It will use a fixed priority of 1.
@return the generated event. Needed in order to remove the event from the dispather
*/
EventListenerCustom* addCustomEventListener(const std::string &eventName, std::function<void(EventCustom*)> callback);
/** Remove a listener
* @param listener The specified event listener which needs to be removed.
*/
void removeEventListener(EventListener* listener);
/** Removes all listeners with the same event listener type */
void removeEventListeners(EventListener::Type listenerType);
/** Removes all custom listeners with the same event name */
void removeCustomEventListeners(const std::string& customEventName);
/** Removes all listeners */
void removeAllEventListeners();
@ -97,13 +105,16 @@ public:
* event dispatcher list.
*/
void dispatchEvent(Event* event);
/** Dispatches a Custom Event with a event name an optional user data */
void dispatchCustomEvent(const std::string &eventName, void *optionalUserData);
/** Constructor of EventDispatcher */
EventDispatcher();
/** Destructor of EventDispatcher */
~EventDispatcher();
private:
protected:
friend class Node;
/** Sets the dirty flag for a node. */
@ -148,22 +159,22 @@ private:
void addEventListener(EventListener* listener);
/** Gets event the listener list for the event listener type. */
EventListenerVector* getListeners(EventListener::ListenerID listenerID);
EventListenerVector* getListeners(const EventListener::ListenerID& listenerID);
/** Update dirty flag */
void updateDirtyFlagForSceneGraph();
/** Removes all listeners with the same event listener ID */
void removeEventListenersForListenerID(EventListener::ListenerID listenerID);
void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID);
/** Sort event listener */
void sortEventListeners(EventListener::ListenerID listenerID);
void sortEventListeners(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by scene graph priority */
void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID);
void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by fixed priority */
void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID);
void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID);
/** Updates all listeners
* 1) Removes all listener items that have been marked as 'removed' when dispatching event.
@ -193,12 +204,11 @@ private:
};
/** Sets the dirty flag for a specified listener ID */
void setDirty(EventListener::ListenerID listenerID, DirtyFlag flag);
void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag);
/** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
void visitTarget(Node* node);
private:
/** Listeners map */
std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners;

View File

@ -57,7 +57,7 @@ public:
CUSTOM
};
typedef std::size_t ListenerID;
typedef std::string ListenerID;
protected:
/** Constructor */
@ -83,7 +83,7 @@ protected:
inline bool isRegistered() const { return _isRegistered; };
inline Type getType() const { return _type; };
inline ListenerID getListenerID() const { return _listenerID; };
inline const ListenerID& getListenerID() const { return _listenerID; };
inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; };
inline int getFixedPriority() const { return _fixedPriority; };

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN
const std::string EventListenerAcceleration::LISTENER_ID = "__cc_acceleration";
EventListenerAcceleration::EventListenerAcceleration()
{
@ -59,7 +61,7 @@ bool EventListenerAcceleration::init(std::function<void(Acceleration*, Event* ev
this->onAccelerationEvent(&accEvent->_acc, event);
};
if (EventListener::init(Type::ACCELERATION, static_cast<ListenerID>(Type::ACCELERATION), listener))
if (EventListener::init(Type::ACCELERATION, LISTENER_ID, listener))
{
onAccelerationEvent = callback;
return true;

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
class EventListenerAcceleration : public EventListener
{
public:
static const std::string LISTENER_ID;
static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback);
virtual ~EventListenerAcceleration();
@ -44,6 +46,8 @@ private:
bool init(std::function<void(Acceleration*, Event* event)> callback);
std::function<void(Acceleration*, Event*)> onAccelerationEvent;
friend class LuaEventListenerAcceleration;
};
NS_CC_END

View File

@ -35,7 +35,7 @@ EventListenerCustom::EventListenerCustom()
EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback)
{
EventListenerCustom* ret = new EventListenerCustom();
if (ret && ret->init(std::hash<std::string>()(eventName), callback))
if (ret && ret->init(eventName, callback))
{
ret->autorelease();
}

View File

@ -70,6 +70,8 @@ protected:
bool init(ListenerID listenerId, std::function<void(EventCustom*)> callback);
std::function<void(EventCustom*)> _onCustomEvent;
friend class LuaEventListenerCustom;
};
NS_CC_END

View File

@ -29,6 +29,8 @@
NS_CC_BEGIN
const std::string EventListenerKeyboard::LISTENER_ID = "__cc_keyboard";
bool EventListenerKeyboard::checkAvailable()
{
if (onKeyPressed == nullptr && onKeyReleased == nullptr)
@ -92,7 +94,7 @@ bool EventListenerKeyboard::init()
}
};
if (EventListener::init(Type::KEYBOARD, static_cast<ListenerID>(Type::KEYBOARD), listener))
if (EventListener::init(Type::KEYBOARD, LISTENER_ID, listener))
{
return true;
}

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerKeyboard : public EventListener
{
public:
static const std::string LISTENER_ID;
static EventListenerKeyboard* create();
/// Overrides

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN
const std::string EventListenerMouse::LISTENER_ID = "__cc_mouse";
bool EventListenerMouse::checkAvailable()
{
return true;
@ -99,7 +101,7 @@ bool EventListenerMouse::init()
}
};
if (EventListener::init(Type::MOUSE, static_cast<ListenerID>(Type::MOUSE), listener))
if (EventListener::init(Type::MOUSE, LISTENER_ID, listener))
{
return true;
}

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerMouse : public EventListener
{
public:
static const std::string LISTENER_ID;
static EventListenerMouse* create();
/// Overrides

View File

@ -30,6 +30,8 @@
NS_CC_BEGIN
const std::string EventListenerTouchOneByOne::LISTENER_ID = "__cc_touch_one_by_one";
EventListenerTouchOneByOne::EventListenerTouchOneByOne()
: onTouchBegan(nullptr)
, onTouchMoved(nullptr)
@ -46,7 +48,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne()
bool EventListenerTouchOneByOne::init()
{
if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast<ListenerID>(Type::TOUCH_ONE_BY_ONE), nullptr))
if (EventListener::init(Type::TOUCH_ONE_BY_ONE, LISTENER_ID, nullptr))
{
return true;
}
@ -107,6 +109,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone()
}
/////////
const std::string EventListenerTouchAllAtOnce::LISTENER_ID = "__cc_touch_all_at_once";
EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce()
: onTouchesBegan(nullptr)
, onTouchesMoved(nullptr)
@ -122,7 +127,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce()
bool EventListenerTouchAllAtOnce::init()
{
if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE), nullptr))
if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, LISTENER_ID, nullptr))
{
return true;
}

View File

@ -36,6 +36,8 @@ NS_CC_BEGIN
class EventListenerTouchOneByOne : public EventListener
{
public:
static const std::string LISTENER_ID;
static EventListenerTouchOneByOne* create();
virtual ~EventListenerTouchOneByOne();
@ -67,8 +69,8 @@ private:
class EventListenerTouchAllAtOnce : public EventListener
{
public:
static const ListenerID ID = static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE);
static const std::string LISTENER_ID;
static EventListenerTouchAllAtOnce* create();
virtual ~EventListenerTouchAllAtOnce();

View File

@ -216,17 +216,17 @@ void GridBase::afterDraw(cocos2d::Node *target)
Director *director = Director::getInstance();
director->setProjection(_directorProjection);
if (target->getCamera()->isDirty())
{
Point offset = target->getAnchorPointInPoints();
//
// XXX: Camera should be applied in the AnchorPoint
//
kmGLTranslatef(offset.x, offset.y, 0);
target->getCamera()->locate();
kmGLTranslatef(-offset.x, -offset.y, 0);
}
// if (target->getCamera()->isDirty())
// {
// Point offset = target->getAnchorPointInPoints();
//
// //
// // XXX: Camera should be applied in the AnchorPoint
// //
// kmGLTranslatef(offset.x, offset.y, 0);
// target->getCamera()->locate();
// kmGLTranslatef(-offset.x, -offset.y, 0);
// }
GL::bindTexture2D(_texture->getName());

View File

@ -27,7 +27,6 @@ THE SOFTWARE.
#include "CCObject.h"
#include "CCNode.h"
#include "CCCamera.h"
#include "ccTypes.h"
#include "CCTexture2D.h"
#include "CCDirector.h"

View File

@ -802,9 +802,9 @@ LayerMultiplex::LayerMultiplex()
LayerMultiplex::~LayerMultiplex()
{
std::for_each(_layers.begin(), _layers.end(), [](Layer* layer){
for(const auto &layer : _layers) {
layer->cleanup();
});
}
}
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)

View File

@ -290,23 +290,16 @@ void Menu::alignItemsVertically()
void Menu::alignItemsVerticallyWithPadding(float padding)
{
float height = -padding;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
{
height += child->getContentSize().height * child->getScaleY() + padding;
}
});
for(const auto &child : _children)
height += child->getContentSize().height * child->getScaleY() + padding;
float y = height / 2.0f;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
{
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
y -= child->getContentSize().height * child->getScaleY() + padding;
}
});
for(const auto &child : _children) {
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
y -= child->getContentSize().height * child->getScaleY() + padding;
}
}
void Menu::alignItemsHorizontally(void)
@ -317,22 +310,15 @@ void Menu::alignItemsHorizontally(void)
void Menu::alignItemsHorizontallyWithPadding(float padding)
{
float width = -padding;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
{
width += child->getContentSize().width * child->getScaleX() + padding;
}
});
for(const auto &child : _children)
width += child->getContentSize().width * child->getScaleX() + padding;
float x = -width / 2.0f;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
{
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
x += child->getContentSize().width * child->getScaleX() + padding;
}
});
for(const auto &child : _children) {
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
x += child->getContentSize().width * child->getScaleX() + padding;
}
}
void Menu::alignItemsInColumns(int columns, ...)
@ -365,29 +351,26 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
int columnsOccupied = 0;
int rowColumns = 0;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
for(const auto &child : _children) {
CCASSERT(row < rows.size(), "");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
CCASSERT(row < rows.size(), "");
height += rowHeight + 5;
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
height += rowHeight + 5;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
columnsOccupied = 0;
rowHeight = 0;
++row;
}
});
}
// check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, "");
@ -401,39 +384,33 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
float x = 0.0;
float y = (float)(height / 2);
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
for(const auto &child : _children) {
if (rowColumns == 0)
{
if (child)
{
if (rowColumns == 0)
{
rowColumns = rows[row].asInt();
w = winSize.width / (1 + rowColumns);
x = w;
}
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
rowColumns = rows[row].asInt();
w = winSize.width / (1 + rowColumns);
x = w;
}
});
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
}
void Menu::alignItemsInRows(int rows, ...)
@ -469,36 +446,33 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
int rowsOccupied = 0;
int columnRows;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
for(const auto &child : _children) {
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
});
}
// check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, "");
@ -511,35 +485,32 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
float x = (float)(-width / 2);
float y = 0.0;
std::for_each(_children.begin(), _children.end(), [&](Node* child){
if (child)
for(const auto &child : _children) {
if (columnRows == 0)
{
if (columnRows == 0)
{
columnRows = columns[column].asInt();
y = (float) columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
columnRows = columns[column].asInt();
y = (float) columnHeights[column];
}
});
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
}
}
MenuItem* Menu::getItemForTouch(Touch *touch)

View File

@ -918,9 +918,9 @@ void MenuItemToggle::addSubItem(MenuItem *item)
MenuItemToggle::~MenuItemToggle()
{
std::for_each(_subItems.begin(), _subItems.end(), [](MenuItem* item){
for(const auto &item : _subItems) {
item->cleanup();
});
}
}
void MenuItemToggle::setSelectedIndex(unsigned int index)
@ -970,9 +970,9 @@ void MenuItemToggle::setEnabled(bool enabled)
{
MenuItem::setEnabled(enabled);
std::for_each(_subItems.begin(), _subItems.end(), [&enabled](MenuItem* item){
for(const auto &item : _subItems) {
item->setEnabled(enabled);
});
}
}
}

View File

@ -30,6 +30,8 @@ THE SOFTWARE.
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCVertex.h"
#include "CCCustomCommand.h"
#include "CCRenderer.h"
NS_CC_BEGIN
@ -322,12 +324,10 @@ void MotionStreak::reset()
_nuPoints = 0;
}
void MotionStreak::draw()
{
if(_nuPoints <= 1)
return;
CC_NODE_DRAW_SETUP();
void MotionStreak::onDraw()
{
getShaderProgram()->use();
getShaderProgram()->setUniformsForBuiltins(_cachedMV);
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
@ -351,8 +351,18 @@ void MotionStreak::draw()
#endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2);
}
void MotionStreak::draw()
{
if(_nuPoints <= 1)
return;
kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV);
CustomCommand* cmd = CustomCommand::getCommandPool().generateCommand();
cmd->init(0,_vertexZ);
cmd->func = CC_CALLBACK_0(MotionStreak::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(cmd);
CC_INCREMENT_GL_DRAWS(1);
}
NS_CC_END

View File

@ -99,6 +99,11 @@ public:
virtual void setOpacityModifyRGB(bool value) override;
virtual bool isOpacityModifyRGB() const override;
protected:
kmMat4 _cachedMV;
//renderer callback
void onDraw();
protected:
/**
* @js ctor

View File

@ -32,7 +32,6 @@ THE SOFTWARE.
#include "CCString.h"
#include "ccCArray.h"
#include "TransformUtils.h"
#include "CCCamera.h"
#include "CCGrid.h"
#include "CCDirector.h"
#include "CCScheduler.h"
@ -106,10 +105,8 @@ Node::Node(void)
, _additionalTransformDirty(false)
, _transformDirty(true)
, _inverseDirty(true)
, _camera(nullptr)
// children (lazy allocs)
// lazy alloc
, _grid(nullptr)
, _ZOrder(0)
, _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
@ -169,9 +166,6 @@ Node::~Node()
CC_SAFE_RELEASE(_eventDispatcher);
// attributes
CC_SAFE_RELEASE(_camera);
CC_SAFE_RELEASE(_grid);
CC_SAFE_RELEASE(_shaderProgram);
CC_SAFE_RELEASE(_userObject);
@ -404,26 +398,6 @@ ssize_t Node::getChildrenCount() const
return _children.size();
}
/// camera getter: lazy alloc
Camera* Node::getCamera()
{
if (!_camera)
{
_camera = new Camera();
}
return _camera;
}
/// grid setter
void Node::setGrid(GridBase* grid)
{
CC_SAFE_RETAIN(grid);
CC_SAFE_RELEASE(_grid);
_grid = grid;
}
/// isVisible getter
bool Node::isVisible() const
{
@ -544,6 +518,13 @@ void Node::setShaderProgram(GLProgram *pShaderProgram)
_shaderProgram = pShaderProgram;
}
Scene* Node::getScene()
{
if(!_parent)
return nullptr;
return _parent->getScene();
}
Rect Node::getBoundingBox() const
{
Rect rect = Rect(0, 0, _contentSize.width, _contentSize.height);
@ -823,11 +804,6 @@ void Node::visit()
kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
this->transform();
int i = 0;
@ -857,11 +833,6 @@ void Node::visit()
// reset for next frame
_orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
}
@ -888,27 +859,10 @@ void Node::transform()
kmGLMultMatrix( &transfrom4x4 );
// saves the MV matrix
kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewTransform);
// XXX: Expensive calls. Camera should be integrated into the cached affine matrix
if ( _camera != nullptr && !(_grid != nullptr && _grid->isActive()) )
{
bool translate = (_anchorPointInPoints.x != 0.0f || _anchorPointInPoints.y != 0.0f);
if( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(_anchorPointInPoints.y), 0 );
_camera->locate();
if( translate )
kmGLTranslatef(RENDER_IN_SUBPIXEL(-_anchorPointInPoints.x), RENDER_IN_SUBPIXEL(-_anchorPointInPoints.y), 0 );
}
}
void Node::onEnter()
{
_isTransitionFinished = false;
@ -1205,10 +1159,12 @@ const kmMat4& Node::getNodeToParentTransform() const
// Build Transform Matrix
// Adjusted transform calculation for rotational skew
_transform = { cy * _scaleX, sy * _scaleX, 0, 0,
kmScalar mat[] = { cy * _scaleX, sy * _scaleX, 0, 0,
-sx * _scaleY, cx * _scaleY, 0, 0,
0, 0, 1, 0,
x, y, 0, 1 };
kmMat4Fill(&_transform, mat);
// XXX: Try to inline skew
// If skew is needed, apply skew and then anchor point
@ -1243,6 +1199,12 @@ const kmMat4& Node::getNodeToParentTransform() const
return _transform;
}
void Node::setNodeToParentTransform(const kmMat4& transform)
{
_transform = transform;
_transformDirty = false;
}
void Node::setAdditionalTransform(const AffineTransform& additionalTransform)
{
CGAffineToGL(additionalTransform, _additionalTransform.mat);

View File

@ -43,7 +43,6 @@
NS_CC_BEGIN
class Camera;
class GridBase;
class Point;
class Touch;
@ -54,6 +53,7 @@ class ActionManager;
class Component;
class ComponentContainer;
class EventDispatcher;
class Scene;
#ifdef CC_USE_PHYSICS
class PhysicsBody;
#endif
@ -98,7 +98,6 @@ class EventListener;
- position
- scale (x, y)
- rotation (in degrees, clockwise)
- Camera (an interface to gluLookAt )
- GridBase (to do mesh transformations)
- anchor point
- size
@ -120,18 +119,14 @@ class EventListener;
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The node will be moved according to the camera values (camera)
Order in transformations with grid enabled
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen
Camera:
- Each node has a camera. By default it points to the center of the Node.
*/
class CC_DLL Node : public Object
@ -702,34 +697,7 @@ public:
virtual void sortAllChildren();
/// @} end of Children and Parent
/// @{
/// @name Grid object for effects
/**
* Returns a grid object that is used when applying effects
*
* @return A Grid object that is used when applying effects
* @js NA
*/
virtual GridBase* getGrid() { return _grid; }
/**
* @js NA
*/
virtual const GridBase* getGrid() const { return _grid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
virtual void setGrid(GridBase *grid);
/// @} end of Grid
/// @{
/// @name Tag & User data
@ -861,19 +829,6 @@ public:
/// @} end of Shader Program
/**
* Returns a camera object that lets you move the node using a gluLookAt
*
@code
Camera* camera = node->getCamera();
camera->setEye(0, 0, 415/2);
camera->setCenter(0, 0, 0);
@endcode
*
* @return A Camera object that lets you move the node using a gluLookAt
*/
virtual Camera* getCamera();
/**
* Returns whether or not the node accepts event callbacks.
*
@ -956,6 +911,11 @@ public:
*/
virtual void visit();
/** Returns the Scene that contains the Node.
It returns `nullptr` if the node doesn't belong to any Scene.
This function recursively calls parent->getScene() until parent is a Scene object. The results are not cached. It is that the user caches the results in case this functions is being used inside a loop.
*/
virtual Scene* getScene();
/**
* Returns a "local" axis aligned bounding box of the node.
@ -1229,6 +1189,11 @@ public:
virtual const kmMat4& getNodeToParentTransform() const;
virtual AffineTransform getNodeToParentAffineTransform() const;
/**
* Sets the Transformation matrix manually.
*/
virtual void setNodeToParentTransform(const kmMat4& transform);
/** @deprecated use getNodeToParentTransform() instead */
CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToParentTransform() const { return getNodeToParentAffineTransform(); }
@ -1464,10 +1429,6 @@ protected:
mutable bool _transformDirty; ///< transform dirty flag
mutable bool _inverseDirty; ///< inverse transform dirty flag
Camera *_camera; ///< a camera
GridBase *_grid; ///< a grid
int _ZOrder; ///< z-order value that affects the draw order
Vector<Node*> _children; ///< array of children nodes

174
cocos/2d/CCNodeGrid.cpp Normal file
View File

@ -0,0 +1,174 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCNodeGrid.h"
#include "CCGrid.h"
#include "CCGroupCommand.h"
#include "CCRenderer.h"
#include "CCCustomCommand.h"
NS_CC_BEGIN
NodeGrid* NodeGrid::create()
{
NodeGrid * ret = new NodeGrid();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
NodeGrid::NodeGrid()
: _nodeGrid(nullptr)
, _gridTarget(nullptr)
{
}
void NodeGrid::setTarget(Node* target)
{
CC_SAFE_RELEASE(_gridTarget);
CC_SAFE_RETAIN(target);
_gridTarget = target;
}
NodeGrid::~NodeGrid()
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RELEASE(_gridTarget);
}
void NodeGrid::onGridBeginDraw()
{
if (_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->beforeDraw();
}
}
void NodeGrid::onGridEndDraw()
{
if(_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->afterDraw(this);
}
}
void NodeGrid::visit()
{
// quick return if not visible. children won't be drawn.
if (!_visible)
{
return;
}
Renderer* renderer = Director::getInstance()->getRenderer();
GroupCommand* groupCommand = GroupCommand::getCommandPool().generateCommand();
groupCommand->init(0,_vertexZ);
renderer->addCommand(groupCommand);
renderer->pushGroup(groupCommand->getRenderQueueID());
kmGLPushMatrix();
Director::Projection beforeProjectionType;
if(_nodeGrid && _nodeGrid->isActive())
{
beforeProjectionType = Director::getInstance()->getProjection();
_nodeGrid->set2DProjection();
}
CustomCommand* gridBeginCmd = CustomCommand::getCommandPool().generateCommand();
gridBeginCmd->init(0,_vertexZ);
gridBeginCmd->func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
renderer->addCommand(gridBeginCmd);
this->transform();
if(_gridTarget)
{
_gridTarget->visit();
}
int i = 0;
if(!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for( ; i < _children.size(); i++ )
{
auto node = _children.at(i);
if ( node && node->getZOrder() < 0 )
node->visit();
else
break;
}
// self draw,currently we have nothing to draw on NodeGrid, so there is no need to add render command
this->draw();
for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) {
(*it)->visit();
}
}
else
{
this->draw();
}
// reset for next frame
_orderOfArrival = 0;
if(_nodeGrid && _nodeGrid->isActive())
{
// restore projection
Director *director = Director::getInstance();
director->setProjection(beforeProjectionType);
}
CustomCommand* gridEndCmd = CustomCommand::getCommandPool().generateCommand();
gridEndCmd->init(0,_vertexZ);
gridEndCmd->func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
renderer->addCommand(gridEndCmd);
renderer->popGroup();
kmGLPopMatrix();
}
void NodeGrid::setGrid(GridBase *grid)
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RETAIN(grid);
_nodeGrid = grid;
}
NS_CC_END

73
cocos/2d/CCNodeGrid.h Normal file
View File

@ -0,0 +1,73 @@
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __MISCNODE_CCGRID_NODE_H__
#define __MISCNODE_CCGRID_NODE_H__
#include "CCNode.h"
#include "kazmath/GL/matrix.h"
NS_CC_BEGIN
class GridBase;
class NodeGrid : public Node
{
public:
static NodeGrid* create();
GridBase* getGrid() { return _nodeGrid; }
/**
* @js NA
*/
const GridBase* getGrid() const { return _nodeGrid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
void setGrid(GridBase *grid);
void setTarget(Node *target);
// overrides
virtual void visit() override;
protected:
NodeGrid();
virtual ~NodeGrid();
void onGridBeginDraw();
void onGridEndDraw();
Node* _gridTarget;
GridBase* _nodeGrid;
private:
CC_DISALLOW_COPY_AND_ASSIGN(NodeGrid);
};
NS_CC_END
#endif

View File

@ -135,21 +135,10 @@ void ParticleBatchNode::visit()
kmGLPushMatrix();
if ( _grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
transform();
draw();
if ( _grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
}
@ -385,9 +374,8 @@ void ParticleBatchNode::removeChildAtIndex(int index, bool doCleanup)
void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{
std::for_each(_children.begin(), _children.end(), [](Node* child){
for(const auto &child : _children)
static_cast<ParticleSystem*>(child)->setBatchNode(nullptr);
});
Node::removeAllChildrenWithCleanup(doCleanup);
@ -481,11 +469,11 @@ void ParticleBatchNode::updateAllAtlasIndexes()
{
int index = 0;
std::for_each(_children.begin(), _children.end(), [&index](Node* child){
for(const auto &child : _children) {
ParticleSystem* partiSys = static_cast<ParticleSystem*>(child);
partiSys->setAtlasIndex(index);
index += partiSys->getTotalParticles();
});
}
}
// ParticleBatchNode - CocosNodeTexture protocol

View File

@ -456,22 +456,11 @@ void RenderTexture::visit()
}
kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
transform();
_sprite->visit();
draw();
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
_orderOfArrival = 0;
@ -529,12 +518,12 @@ void RenderTexture::draw()
//! make sure all children are drawn
sortAllChildren();
std::for_each(_children.begin(), _children.end(), [this](Node* child){
for(const auto &child : _children) {
if (child != _sprite)
{
child->visit();
}
});
}
end();
}

View File

@ -83,6 +83,11 @@ std::string Scene::getDescription() const
return StringUtils::format("<Scene | tag = %d>", _tag);
}
Scene* Scene::getScene()
{
return this;
}
#ifdef CC_USE_PHYSICS
Scene *Scene::createWithPhysics()
{
@ -146,9 +151,9 @@ void Scene::addChildToPhysicsWorld(Node* child)
}
auto& children = node->getChildren();
std::for_each(children.begin(), children.end(), [addToPhysicsWorldFunc](Node* n){
for( const auto &n : children) {
addToPhysicsWorldFunc(n);
});
}
};
addToPhysicsWorldFunc(child);

View File

@ -56,6 +56,8 @@ public:
static Scene *createWithPhysics();
#endif
// Overrides
virtual Scene *getScene() override;
#ifdef CC_USE_PHYSICS
public:
@ -76,6 +78,7 @@ protected:
#endif // CC_USE_PHYSICS
protected:
Scene();
virtual ~Scene();

View File

@ -809,9 +809,9 @@ Vector<Object*> Scheduler::pauseAllTargetsWithMinPriority(int minPriority)
void Scheduler::resumeTargets(const Vector<Object*>& targetsToResume)
{
std::for_each(targetsToResume.begin(), targetsToResume.end(), [this](Object* obj){
for(const auto &obj : targetsToResume) {
this->resumeTarget(obj);
});
}
}
void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)

View File

@ -214,6 +214,12 @@ enum ScriptEventType
kAssetsManagerEvent,//Now it's only used in Lua Binding
kCocoStudioEventListener,//Now it's only used in Lua Binding
kArmatureWrapper,//Now it's only used in Lua Binding
kEventListenerAcc,//Now it's only used in Lua Binding
kEventListenerKeyboard,//Now it's only used in Lua Binding
kEventListenerTouch,//Now it's only used in Lua Binding
kEventListenerTouches,//Now it's only used in Lua Binding
kEventListenerMouse,//Now it's only used in Lua Binding
kEventListenerCustom,////Now it's only used in Lua Binding
};
struct BasicScriptData

View File

@ -528,7 +528,7 @@ void Sprite::updateTransform(void)
CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite");
kmMat4 nodeToParent = getNodeToParentTransform();
kmMat4 parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch;
kmMat4Multiply(&_transformToBatch, &nodeToParent, &parentTransform);
kmMat4Multiply(&_transformToBatch, &parentTransform, &nodeToParent);
}
//

View File

@ -146,21 +146,10 @@ void SpriteBatchNode::visit(void)
kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
transformAncestors();
}
sortAllChildren();
transform();
draw();
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
setOrderOfArrival(0);
@ -225,9 +214,9 @@ void SpriteBatchNode::removeAllChildrenWithCleanup(bool doCleanup)
{
// Invalidate atlas index. issue #569
// useSelfRender should be performed on all descendants. issue #1216
std::for_each(_descendants.begin(), _descendants.end(), [](Sprite* sprite) {
for(const auto &sprite: _descendants) {
sprite->setBatchNode(nullptr);
});
}
Node::removeAllChildrenWithCleanup(doCleanup);
@ -240,48 +229,24 @@ void SpriteBatchNode::sortAllChildren()
{
if (_reorderChildDirty)
{
#if 0
int i = 0,j = 0,length = _children->count();
// insertion sort
for(i=1; i<length; i++)
{
j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() ||
( tempI->getZOrder() == tempJ->getZOrder() &&
tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) )
{
_children->fastSetObject( tempJ, j+1 );
j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
}
_children->fastSetObject(tempI, j+1);
}
#else
std::sort(std::begin(_children), std::end(_children), nodeComparisonLess);
#endif
//sorted now check all children
if (!_children.empty())
{
//first sort all children recursively based on zOrder
std::for_each(_children.begin(), _children.end(), [](Node* child){
for(const auto &child: _children) {
child->sortAllChildren();
});
}
ssize_t index=0;
//fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
// and at the same time reorder descendants and the quads to the right index
std::for_each(_children.begin(), _children.end(), [this, &index](Node* child){
for(const auto &child: _children) {
Sprite* sp = static_cast<Sprite*>(child);
updateAtlasIndex(sp, &index);
});
}
}
_reorderChildDirty=false;
@ -324,7 +289,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
needNewIndex = false;
}
std::for_each(array.begin(), array.end(), [&](Node* child){
for(const auto &child: array) {
Sprite* sp = static_cast<Sprite*>(child);
if (needNewIndex && sp->getZOrder() >= 0)
{
@ -339,7 +304,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex)
}
updateAtlasIndex(sp, curIndex);
});
}
if (needNewIndex)
{//all children have a zOrder < 0)
@ -390,9 +355,9 @@ void SpriteBatchNode::draw(void)
CC_NODE_DRAW_SETUP();
std::for_each(_children.begin(), _children.end(), [](Node* child){
for(const auto &child: _children) {
child->updateTransform();
});
}
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
@ -425,14 +390,13 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
CCASSERT(index>=0 && index < _children.size(), "Invalid index");
auto& children = parent->getChildren();
std::for_each(children.begin(), children.end(), [this, &index](Node* child){
for(const auto &child: children) {
Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() < 0))
{
index = rebuildIndexInOrder(sp, index);
}
});
}
// ignore self (batch node)
if (! parent->isEqual(this))
@ -441,13 +405,13 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index)
index++;
}
std::for_each(children.begin(), children.end(), [this, &index](Node* child){
for(const auto &child: children) {
Sprite* sp = static_cast<Sprite*>(child);
if (sp && (sp->getZOrder() >= 0))
{
index = rebuildIndexInOrder(sp, index);
}
});
}
return index;
}
@ -560,9 +524,9 @@ void SpriteBatchNode::appendChild(Sprite* sprite)
// add children recursively
auto& children = sprite->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* child){
for(const auto &child: children) {
appendChild(static_cast<Sprite*>(child));
});
}
}
void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
@ -578,22 +542,23 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
{
auto next = std::next(it);
std::for_each(next, _descendants.end(), [](Sprite *spr) {
for(; next != _descendants.end(); ++next) {
Sprite *spr = *next;
spr->setAtlasIndex( spr->getAtlasIndex() - 1 );
});
}
_descendants.erase(it);
}
// remove children recursively
auto& children = sprite->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* obj){
for(const auto &obj: children) {
Sprite* child = static_cast<Sprite*>(obj);
if (child)
{
removeSpriteFromAtlas(child);
}
});
}
}
void SpriteBatchNode::updateBlendFunc(void)
@ -686,10 +651,10 @@ SpriteBatchNode * SpriteBatchNode::addSpriteWithoutQuad(Sprite*child, int z, int
// XXX: optimize with a binary search
auto it = std::begin(_descendants);
std::for_each(_descendants.begin(), _descendants.end(), [&](Sprite *sprite) {
for(const auto &sprite: _descendants) {
if(sprite->getAtlasIndex() >= z)
std::next(it);
});
}
_descendants.insert(it, child);

View File

@ -172,7 +172,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu
// get aliases
ValueVector& aliases = frameDict["aliases"].asValueVector();
std::for_each(aliases.cbegin(), aliases.cend(), [this, &spriteFrameName](const Value& value){
for(const auto &value : aliases) {
std::string oneAlias = value.asString();
if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
{
@ -180,7 +180,7 @@ void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Textu
}
_spriteFramesAliases[oneAlias] = Value(spriteFrameName);
});
}
// create frame
spriteFrame = new SpriteFrame();

View File

@ -380,17 +380,14 @@ Sprite * TMXLayer::insertTileForGID(int gid, const Point& pos)
// update possible children
std::for_each(_children.begin(), _children.end(), [&indexForZ](Node* child){
for(const auto &child : _children) {
Sprite* sp = static_cast<Sprite*>(child);
if (child)
ssize_t ai = sp->getAtlasIndex();
if ( ai >= indexForZ )
{
ssize_t ai = sp->getAtlasIndex();
if ( ai >= indexForZ )
{
sp->setAtlasIndex(ai+1);
}
sp->setAtlasIndex(ai+1);
}
});
}
_tiles[z] = gid;
return tile;
@ -399,7 +396,7 @@ Sprite * TMXLayer::insertTileForGID(int gid, const Point& pos)
return nullptr;
}
Sprite * TMXLayer::updateTileForGID(int gid, const Point& pos)
Sprite * TMXLayer::updateTileForGID(int gid, const Point& pos)
{
Rect rect = _tileSet->rectForGID(gid);
rect = Rect(rect.origin.x / _contentScaleFactor, rect.origin.y / _contentScaleFactor, rect.size.width/ _contentScaleFactor, rect.size.height/ _contentScaleFactor);
@ -593,17 +590,14 @@ void TMXLayer::removeTileAt(const Point& pos)
_textureAtlas->removeQuadAtIndex(atlasIndex);
// update possible children
std::for_each(_children.begin(), _children.end(), [&atlasIndex](Node* obj){
for(const auto &obj : _children) {
Sprite* child = static_cast<Sprite*>(obj);
if (child)
ssize_t ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{
ssize_t ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{
child->setAtlasIndex(ai-1);
}
child->setAtlasIndex(ai-1);
}
});
}
}
}
}

View File

@ -169,8 +169,8 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
int idx=0;
auto& layers = mapInfo->getLayers();
std::for_each(layers.begin(), layers.end(), [&idx, this, &mapInfo](TMXLayerInfo* layerInfo){
if (layerInfo && layerInfo->_visible)
for(const auto &layerInfo : layers) {
if (layerInfo->_visible)
{
TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx);
@ -184,7 +184,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
idx++;
}
});
}
}
// public

View File

@ -25,7 +25,6 @@ THE SOFTWARE.
****************************************************************************/
#include "CCTransition.h"
#include "CCCamera.h"
#include "CCDirector.h"
#include "CCActionInterval.h"
#include "CCActionInstant.h"
@ -35,6 +34,8 @@ THE SOFTWARE.
#include "CCActionGrid.h"
#include "CCLayer.h"
#include "CCRenderTexture.h"
#include "CCNodeGrid.h"
#include "CCNewRenderTexture.h"
NS_CC_BEGIN
@ -112,22 +113,24 @@ void TransitionScene::draw()
void TransitionScene::finish()
{
// clean up
_inScene->setVisible(true);
_inScene->setPosition(Point(0,0));
_inScene->setScale(1.0f);
_inScene->setRotation(0.0f);
_inScene->getCamera()->restore();
_outScene->setVisible(false);
_outScene->setPosition(Point(0,0));
_outScene->setScale(1.0f);
_outScene->setRotation(0.0f);
_outScene->getCamera()->restore();
kmMat4 identity;
kmMat4Identity(&identity);
// clean up
_inScene->setVisible(true);
_inScene->setPosition(Point(0,0));
_inScene->setScale(1.0f);
_inScene->setRotation(0.0f);
_inScene->setAdditionalTransform(identity);
_outScene->setVisible(false);
_outScene->setPosition(Point(0,0));
_outScene->setScale(1.0f);
_outScene->setRotation(0.0f);
_outScene->setAdditionalTransform(identity);
//[self schedule:@selector(setNewScene:) interval:0];
this->schedule(schedule_selector(TransitionScene::setNewScene), 0);
}
void TransitionScene::setNewScene(float dt)
@ -1256,7 +1259,7 @@ TransitionCrossFade* TransitionCrossFade::create(float t, Scene* scene)
return nullptr;
}
void TransitionCrossFade:: draw()
void TransitionCrossFade::draw()
{
// override draw since both scenes (textures) are rendered in 1 scene
}
@ -1272,7 +1275,7 @@ void TransitionCrossFade::onEnter()
LayerColor* layer = LayerColor::create(color);
// create the first render texture for inScene
RenderTexture* inTexture = RenderTexture::create((int)size.width, (int)size.height);
RenderTexture* inTexture = NewRenderTexture::create((int)size.width, (int)size.height);
if (nullptr == inTexture)
{
@ -1289,7 +1292,7 @@ void TransitionCrossFade::onEnter()
inTexture->end();
// create the second render texture for outScene
RenderTexture* outTexture = RenderTexture::create((int)size.width, (int)size.height);
RenderTexture* outTexture = NewRenderTexture::create((int)size.width, (int)size.height);
outTexture->getSprite()->setAnchorPoint( Point(0.5f,0.5f) );
outTexture->setPosition( Point(size.width/2, size.height/2) );
outTexture->setAnchorPoint( Point(0.5f,0.5f) );
@ -1346,10 +1349,13 @@ void TransitionCrossFade::onExit()
//
TransitionTurnOffTiles::TransitionTurnOffTiles()
{
_outSceneProxy = NodeGrid::create();
_outSceneProxy->retain();
}
TransitionTurnOffTiles::~TransitionTurnOffTiles()
{
CC_SAFE_RELEASE(_outSceneProxy);
}
TransitionTurnOffTiles* TransitionTurnOffTiles::create(float t, Scene* scene)
@ -1373,6 +1379,9 @@ void TransitionTurnOffTiles::sceneOrder()
void TransitionTurnOffTiles::onEnter()
{
TransitionScene::onEnter();
_outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize();
float aspect = s.width / s.height;
int x = (int)(12 * aspect);
@ -1380,7 +1389,7 @@ void TransitionTurnOffTiles::onEnter()
TurnOffTiles* toff = TurnOffTiles::create(_duration, Size(x,y));
ActionInterval* action = easeActionWithAction(toff);
_outScene->runAction
_outSceneProxy->runAction
(
Sequence::create
(
@ -1392,6 +1401,29 @@ void TransitionTurnOffTiles::onEnter()
);
}
void TransitionTurnOffTiles::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
TransitionScene::onExit();
}
void TransitionTurnOffTiles::draw()
{
Scene::draw();
if( _isInSceneOnTop )
{
_outSceneProxy->visit();
_inScene->visit();
}
else
{
_inScene->visit();
_outSceneProxy->visit();
}
}
ActionInterval* TransitionTurnOffTiles:: easeActionWithAction(ActionInterval* action)
{
@ -1403,9 +1435,12 @@ ActionInterval* TransitionTurnOffTiles:: easeActionWithAction(ActionInterval* ac
//
TransitionSplitCols::TransitionSplitCols()
{
_gridProxy = NodeGrid::create();
_gridProxy->retain();
}
TransitionSplitCols::~TransitionSplitCols()
{
CC_SAFE_RELEASE(_gridProxy);
}
TransitionSplitCols* TransitionSplitCols::create(float t, Scene* scene)
@ -1423,18 +1458,20 @@ TransitionSplitCols* TransitionSplitCols::create(float t, Scene* scene)
void TransitionSplitCols::onEnter()
{
TransitionScene::onEnter();
_inScene->setVisible(false);
_gridProxy->setTarget(_outScene);
_gridProxy->onEnter();
ActionInterval* split = action();
ActionInterval* seq = (ActionInterval*)Sequence::create
(
split,
CallFunc::create(CC_CALLBACK_0(TransitionScene::hideOutShowIn,this)),
CallFunc::create(CC_CALLBACK_0(TransitionSplitCols::switchTargetToInscene,this)),
split->reverse(),
nullptr
);
this->runAction
_gridProxy->runAction
(
Sequence::create
(
@ -1446,6 +1483,24 @@ void TransitionSplitCols::onEnter()
);
}
void TransitionSplitCols::switchTargetToInscene()
{
_gridProxy->setTarget(_inScene);
}
void TransitionSplitCols::draw()
{
Scene::draw();
_gridProxy->visit();
}
void TransitionSplitCols::onExit()
{
_gridProxy->setTarget(nullptr);
_gridProxy->onExit();
TransitionScene::onExit();
}
ActionInterval* TransitionSplitCols:: action()
{
return SplitCols::create(_duration/2.0f, 3);
@ -1491,9 +1546,12 @@ TransitionSplitRows* TransitionSplitRows::create(float t, Scene* scene)
//
TransitionFadeTR::TransitionFadeTR()
{
_outSceneProxy = NodeGrid::create();
_outSceneProxy->retain();
}
TransitionFadeTR::~TransitionFadeTR()
{
CC_SAFE_RELEASE(_outSceneProxy);
}
TransitionFadeTR* TransitionFadeTR::create(float t, Scene* scene)
@ -1517,6 +1575,9 @@ void TransitionFadeTR::onEnter()
{
TransitionScene::onEnter();
_outSceneProxy->setTarget(_outScene);
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize();
float aspect = s.width / s.height;
int x = (int)(12 * aspect);
@ -1524,7 +1585,7 @@ void TransitionFadeTR::onEnter()
ActionInterval* action = actionWithSize(Size(x,y));
_outScene->runAction
_outSceneProxy->runAction
(
Sequence::create
(
@ -1536,6 +1597,28 @@ void TransitionFadeTR::onEnter()
);
}
void TransitionFadeTR::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
TransitionScene::onExit();
}
void TransitionFadeTR::draw()
{
Scene::draw();
if( _isInSceneOnTop )
{
_outSceneProxy->visit();
_inScene->visit();
}
else
{
_inScene->visit();
_outSceneProxy->visit();
}
}
ActionInterval* TransitionFadeTR::actionWithSize(const Size& size)
{

View File

@ -43,6 +43,7 @@ NS_CC_BEGIN
class ActionInterval;
class Node;
class NodeGrid;
/** @brief TransitionEaseScene can ease the actions of the scene protocol.
@since v0.8.2
@ -643,13 +644,16 @@ public :
* @lua NA
*/
virtual void onEnter() override;
virtual void onExit() override;
virtual ActionInterval * easeActionWithAction(ActionInterval * action) override;
virtual void draw() override;
protected:
TransitionTurnOffTiles();
virtual ~TransitionTurnOffTiles();
virtual void sceneOrder() override;
NodeGrid* _outSceneProxy;
private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionTurnOffTiles);
@ -674,11 +678,13 @@ public:
*/
virtual void onEnter() override;
virtual ActionInterval * easeActionWithAction(ActionInterval * action) override;
virtual void onExit() override;
virtual void draw() override;
protected:
TransitionSplitCols();
virtual ~TransitionSplitCols();
void switchTargetToInscene();
NodeGrid* _gridProxy;
private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionSplitCols);
};
@ -723,13 +729,16 @@ public:
*/
virtual void onEnter() override;
virtual ActionInterval* easeActionWithAction(ActionInterval * action) override;
virtual void onExit() override;
virtual void draw() override;
protected:
TransitionFadeTR();
virtual ~TransitionFadeTR();
virtual void sceneOrder();
NodeGrid* _outSceneProxy;
private:
CC_DISALLOW_COPY_AND_ASSIGN(TransitionFadeTR);
};

View File

@ -29,6 +29,7 @@ THE SOFTWARE.
#include "CCActionInstant.h"
#include "CCActionGrid.h"
#include "CCActionPageTurn3D.h"
#include "CCNodeGrid.h"
NS_CC_BEGIN
@ -37,10 +38,17 @@ float TransitionPageTurn::POLYGON_OFFSET_UNITS = -20.f;
TransitionPageTurn::TransitionPageTurn()
{
_inSceneProxy = NodeGrid::create();
_outSceneProxy = NodeGrid::create();
_inSceneProxy->retain();
_outSceneProxy->retain();
}
TransitionPageTurn::~TransitionPageTurn()
{
CC_SAFE_RELEASE(_inSceneProxy);
CC_SAFE_RELEASE(_outSceneProxy);
}
/** creates a base transition with duration and incoming scene */
@ -75,17 +83,17 @@ void TransitionPageTurn::draw()
Scene::draw();
if( _isInSceneOnTop ) {
_outScene->visit();
_outSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_inScene->visit();
_inSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0);
} else {
_inScene->visit();
_inSceneProxy->visit();
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_outScene->visit();
_outSceneProxy->visit();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0);
}
@ -94,6 +102,13 @@ void TransitionPageTurn::draw()
void TransitionPageTurn::onEnter()
{
TransitionScene::onEnter();
_inSceneProxy->setTarget(_inScene);
_outSceneProxy->setTarget(_outScene);
_inSceneProxy->onEnter();
_outSceneProxy->onEnter();
Size s = Director::getInstance()->getWinSize();
int x,y;
if (s.width > s.height)
@ -111,7 +126,7 @@ void TransitionPageTurn::onEnter()
if (! _back )
{
_outScene->runAction
_outSceneProxy->runAction
(
Sequence::create
(
@ -125,8 +140,8 @@ void TransitionPageTurn::onEnter()
else
{
// to prevent initial flicker
_inScene->setVisible(false);
_inScene->runAction
_inSceneProxy->setVisible(false);
_inSceneProxy->runAction
(
Sequence::create
(
@ -139,7 +154,15 @@ void TransitionPageTurn::onEnter()
);
}
}
void TransitionPageTurn::onExit()
{
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->setTarget(nullptr);
_outSceneProxy->onExit();
_inSceneProxy->onExit();
TransitionScene::onExit();
}
ActionInterval* TransitionPageTurn:: actionWithSize(const Size& vector)
{

View File

@ -30,6 +30,8 @@ THE SOFTWARE.
NS_CC_BEGIN
class NodeGrid;
/**
* @addtogroup transition
* @{
@ -83,11 +85,14 @@ public:
// Overrides
//
virtual void onEnter() override;
virtual void onExit() override;
protected:
virtual void sceneOrder() override;
protected:
NodeGrid* _inSceneProxy;
NodeGrid* _outSceneProxy;
bool _back;
static float POLYGON_OFFSET_FACTOR;
static float POLYGON_OFFSET_UNITS;

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include "CCLayer.h"
#include "CCActionInstant.h"
#include "CCActionProgressTimer.h"
#include "CCNewRenderTexture.h"
NS_CC_BEGIN
@ -71,7 +72,7 @@ void TransitionProgress::onEnter()
Size size = Director::getInstance()->getWinSize();
// create the second render texture for outScene
RenderTexture *texture = RenderTexture::create((int)size.width, (int)size.height);
RenderTexture *texture = NewRenderTexture::create((int)size.width, (int)size.height);
texture->getSprite()->setAnchorPoint(Point(0.5f,0.5f));
texture->setPosition(Point(size.width/2, size.height/2));
texture->setAnchorPoint(Point(0.5f,0.5f));

View File

@ -140,23 +140,16 @@ static void setValueForKey(const char* pKey, const char* pValue)
* implements of UserDefault
*/
UserDefault* UserDefault::_userDefault = 0;
UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault()
{
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
}
UserDefault::UserDefault()
{
_userDefault = nullptr;
}
bool UserDefault::getBoolForKey(const char* pKey)
@ -433,7 +426,7 @@ UserDefault* UserDefault::getInstance()
void UserDefault::destroyInstance()
{
_userDefault = nullptr;
CC_SAFE_DELETE(_userDefault);
}
// XXX: deprecated

View File

@ -46,12 +46,6 @@ NS_CC_BEGIN
class CC_DLL UserDefault
{
public:
/**
* @js NA
* @lua NA
*/
~UserDefault();
// get value methods
/**
@ -186,6 +180,8 @@ public:
private:
UserDefault();
~UserDefault();
static bool createXMLFile();
static void initXMLFilePath();

View File

@ -48,7 +48,7 @@ NS_CC_BEGIN
* implements of UserDefault
*/
UserDefault* UserDefault::_userDefault = 0;
UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;
@ -134,19 +134,12 @@ static void deleteNodeByKey(const char *pKey)
}
#endif
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault()
{
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
}
UserDefault::UserDefault()
{
_userDefault = nullptr;
}
bool UserDefault::getBoolForKey(const char* pKey)
@ -503,8 +496,7 @@ UserDefault* UserDefault::getInstance()
void UserDefault::destroyInstance()
{
delete _userDefault;
_userDefault = nullptr;
CC_SAFE_DELETE(_userDefault);
}
// XXX: deprecated

View File

@ -49,7 +49,7 @@ NS_CC_BEGIN
* implements of UserDefault
*/
UserDefault* UserDefault::_userDefault = 0;
UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;
@ -135,19 +135,12 @@ static void deleteNodeByKey(const char *pKey)
}
#endif
/**
* If the user invoke delete UserDefault::getInstance(), should set _userDefault
* to null to avoid error when he invoke UserDefault::getInstance() later.
*/
UserDefault::~UserDefault()
{
CC_SAFE_DELETE(_userDefault);
_userDefault = nullptr;
}
UserDefault::UserDefault()
{
_userDefault = nullptr;
}
// XXX: deprecated
@ -158,7 +151,7 @@ void UserDefault::purgeSharedUserDefault()
void UserDefault::destroyInstance()
{
_userDefault = nullptr;
CC_SAFE_DELETE(_userDefault);
}
bool UserDefault::getBoolForKey(const char* pKey)

View File

@ -63,6 +63,7 @@ set(COCOS2D_SRC
CCDrawNode.cpp
CCGrabber.cpp
CCGrid.cpp
CCNodeGrid.cpp
CCFont.cpp
CCFontAtlas.cpp
CCFontAtlasCache.cpp
@ -126,7 +127,6 @@ set(COCOS2D_SRC
ccGLStateCache.cpp
CCShaderCache.cpp
ccShaders.cpp
CCCamera.cpp
CCConfiguration.cpp
CCDirector.cpp
CCScheduler.cpp

View File

@ -254,7 +254,6 @@ THE SOFTWARE.
#include "CCEventListenerCustom.h"
// root
#include "CCCamera.h"
#include "CCConfiguration.h"
#include "CCDirector.h"
#include "CCScheduler.h"

View File

@ -222,7 +222,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCAnimation.cpp" />
<ClCompile Include="CCAnimationCache.cpp" />
<ClCompile Include="CCAtlasNode.cpp" />
<ClCompile Include="CCCamera.cpp" />
<ClCompile Include="ccCArray.cpp" />
<ClCompile Include="CCClippingNode.cpp" />
<ClCompile Include="CCComponent.cpp" />
@ -257,6 +256,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="ccGLStateCache.cpp" />
<ClCompile Include="CCGrabber.cpp" />
<ClCompile Include="CCGrid.cpp" />
<ClCompile Include="CCNodeGrid.cpp" />
<ClCompile Include="CCIMEDispatcher.cpp" />
<ClCompile Include="CCLabel.cpp" />
<ClCompile Include="CCLabelAtlas.cpp" />
@ -405,7 +405,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCAnimation.h" />
<ClInclude Include="CCAnimationCache.h" />
<ClInclude Include="CCAtlasNode.h" />
<ClInclude Include="CCCamera.h" />
<ClInclude Include="ccCArray.h" />
<ClInclude Include="CCClippingNode.h" />
<ClInclude Include="CCComponent.h" />
@ -442,6 +441,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="ccGLStateCache.h" />
<ClInclude Include="CCGrabber.h" />
<ClInclude Include="CCGrid.h" />
<ClInclude Include="CCNodeGrid.h" />
<ClInclude Include="CCIMEDelegate.h" />
<ClInclude Include="CCIMEDispatcher.h" />
<ClInclude Include="CCLabel.h" />

View File

@ -453,7 +453,6 @@
<ClCompile Include="CCParallaxNode.cpp">
<Filter>tilemap_parallax_nodes</Filter>
</ClCompile>
<ClCompile Include="CCCamera.cpp" />
<ClCompile Include="CCConfiguration.cpp" />
<ClCompile Include="CCDeprecated.cpp" />
<ClCompile Include="CCDirector.cpp" />
@ -569,6 +568,9 @@
<ClCompile Include="..\base\CCValue.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="CCNodeGrid.cpp">
<Filter>misc_nodes</Filter>
</ClCompile>
<ClCompile Include="..\..\external\edtaa3func\edtaa3func.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
@ -1048,7 +1050,6 @@
<ClInclude Include="CCParallaxNode.h">
<Filter>tilemap_parallax_nodes</Filter>
</ClInclude>
<ClInclude Include="CCCamera.h" />
<ClInclude Include="CCConfiguration.h" />
<ClInclude Include="CCDirector.h" />
<ClInclude Include="ccFPSImages.h" />
@ -1188,6 +1189,9 @@
<ClInclude Include="..\base\CCVector.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="CCNodeGrid.h">
<Filter>misc_nodes</Filter>
</ClInclude>
<ClInclude Include="..\..\external\edtaa3func\edtaa3func.h">
<Filter>label_nodes</Filter>
</ClInclude>

View File

@ -321,8 +321,8 @@ ValueVector FileUtils::getValueVectorFromFile(const std::string& filename)
/*
* forward statement
*/
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *doc);
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *doc);
static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *doc);
static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc);
/*
* Use tinyxml2 to write plist files
@ -371,7 +371,7 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath)
/*
* Generate tinyxml2::XMLElement for Object through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XMLDocument *doc)
static tinyxml2::XMLElement* generateElementForObject(const Value& value, tinyxml2::XMLDocument *doc)
{
// object is String
if (value.getType() == Value::Type::STRING)
@ -417,7 +417,7 @@ static tinyxml2::XMLElement* generateElementForObject(Value& value, tinyxml2::XM
/*
* Generate tinyxml2::XMLElement for Dictionary through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XMLDocument *doc)
static tinyxml2::XMLElement* generateElementForDict(const ValueMap& dict, tinyxml2::XMLDocument *doc)
{
tinyxml2::XMLElement* rootNode = doc->NewElement("dict");
@ -438,16 +438,15 @@ static tinyxml2::XMLElement* generateElementForDict(ValueMap& dict, tinyxml2::XM
/*
* Generate tinyxml2::XMLElement for Array through a tinyxml2::XMLDocument
*/
static tinyxml2::XMLElement* generateElementForArray(ValueVector& array, tinyxml2::XMLDocument *pDoc)
static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, tinyxml2::XMLDocument *pDoc)
{
tinyxml2::XMLElement* rootNode = pDoc->NewElement("array");
std::for_each(array.begin(), array.end(), [=](Value& value){
for(const auto &value : array) {
tinyxml2::XMLElement *element = generateElementForObject(value, pDoc);
if (element)
rootNode->LinkEndChild(element);
});
}
return rootNode;
}

View File

@ -190,7 +190,7 @@ double getDoubleForKeyJNI(const char* pKey, double defaultValue)
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getDoubleForKey", "(Ljava/lang/String;D)D")) {
jstring stringArg = t.env->NewStringUTF(pKey);
jdouble ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, stringArg);
jdouble ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, stringArg, defaultValue);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);

View File

@ -38,7 +38,7 @@ THE SOFTWARE.
NS_CC_BEGIN
static void addValueToDict(id nsKey, id nsValue, ValueMap& dict);
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict);
static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict);
static void addItemToArray(id item, ValueVector& array)
{
@ -83,7 +83,7 @@ static void addItemToArray(id item, ValueVector& array)
}
}
static void addObjectToNSArray(Value& value, NSMutableArray *array)
static void addObjectToNSArray(const Value& value, NSMutableArray *array)
{
// add string into array
if (value.getType() == Value::Type::STRING)
@ -100,9 +100,10 @@ static void addObjectToNSArray(Value& value, NSMutableArray *array)
ValueVector valueArray = value.asValueVector();
std::for_each(valueArray.begin(), valueArray.end(), [=](Value& e){
for (const auto &e : valueArray)
{
addObjectToNSArray(e, element);
});
}
[array addObject:element];
return;
@ -171,7 +172,7 @@ static void addValueToDict(id nsKey, id nsValue, ValueMap& dict)
}
}
static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDictionary *dict)
static void addObjectToNSDict(const std::string& key, const Value& value, NSMutableDictionary *dict)
{
NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding];
@ -204,9 +205,10 @@ static void addObjectToNSDict(const std::string& key, Value& value, NSMutableDic
ValueVector array = value.asValueVector();
std::for_each(array.begin(), array.end(), [=](Value& v){
for(const auto& v : array)
{
addObjectToNSArray(v, arrElement);
});
}
[dict setObject:arrElement forKey:NSkey];
return;

View File

@ -68,6 +68,7 @@ int GroupCommandManager::getGroupID()
{
if(!it->second)
{
_groupMapping[it->first] = true;
return it->first;
}
}

View File

@ -296,7 +296,10 @@ void Renderer::render()
//TODO give command back to command pool
for (size_t j = 0 ; j < _renderGroups.size(); j++)
{
for_each(_renderGroups[j].begin(), _renderGroups[j].end(), [](RenderCommand* cmd){ cmd->releaseToCommandPool(); });
for (const auto &cmd : _renderGroups[j])
{
cmd->releaseToCommandPool();
}
_renderGroups[j].clear();
}

View File

@ -26,7 +26,6 @@ THE SOFTWARE.
#include "CCArray.h"
#include "CCString.h"
#include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
NS_CC_BEGIN
@ -481,10 +480,10 @@ __Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName)
ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName);
__Array* ret = __Array::createWithCapacity(static_cast<int>(arr.size()));
std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){
for(const auto &value : arr) {
ret->addObject(__String::create(value.asString()));
});
}
return ret;
}

View File

@ -64,14 +64,14 @@ void AutoreleasePool::clear()
int nIndex = _managedObjectArray.size() - 1;
#endif
std::for_each(_managedObjectArray.rbegin(), _managedObjectArray.rend(), [&](Object* obj){
for(const auto &obj : _managedObjectArray) {
--(obj->_autoReleaseCount);
//(*it)->release();
//delete (*it);
#ifdef _DEBUG
nIndex--;
#endif
});
}
_managedObjectArray.clear();
}
@ -118,9 +118,9 @@ void PoolManager::finalize()
{
if (!_releasePoolStack.empty())
{
std::for_each(_releasePoolStack.begin(), _releasePoolStack.end(), [](AutoreleasePool* pool){
for(const auto &pool : _releasePoolStack) {
pool->clear();
});
}
}
}

View File

@ -26,7 +26,6 @@
#include "CCString.h"
#include "CCInteger.h"
#include "platform/CCFileUtils.h"
#include <algorithm> // std::for_each
using namespace std;
@ -415,8 +414,8 @@ static __Array* visitArray(const ValueVector& array)
{
__Array* ret = new __Array();
ret->init();
std::for_each(array.begin(), array.end(), [&ret](const Value& value){
for(const auto &value : array) {
if (value.getType() == Value::Type::MAP)
{
const ValueMap& subDict = value.asValueMap();
@ -437,7 +436,7 @@ static __Array* visitArray(const ValueVector& array)
ret->addObject(str);
str->release();
}
});
}
return ret;
}

View File

@ -29,7 +29,6 @@
#include <vector>
#include <unordered_map>
#include <algorithm> // std::for_each
NS_CC_BEGIN
@ -241,9 +240,9 @@ public:
*/
void erase(const std::vector<K>& keys)
{
std::for_each(keys.cbegin(), keys.cend(), [this](const K& key){
for(const auto &key : keys) {
this->erase(key);
});
}
}
/** All the elements in the Map<K,V> container are dropped:

View File

@ -29,7 +29,7 @@ THE SOFTWARE.
#include <vector>
#include <functional>
#include <algorithm> // std::for_each
#include <algorithm> // for std::find
NS_CC_BEGIN
@ -267,10 +267,10 @@ public:
/** Push all elements of an existing vector to the end of current vector. */
void pushBack(const Vector<T>& other)
{
std::for_each(other.begin(), other.end(), [this](T obj){
for(const auto &obj : other) {
_data.push_back(obj);
obj->retain();
});
}
}
/** @brief Insert a certain object at a certain index
@ -415,9 +415,9 @@ protected:
/** Retains all the objects in the vector */
void addRefForAllObjects()
{
std::for_each(_data.begin(), _data.end(), [](T obj){
for(const auto &obj : _data) {
obj->retain();
});
}
}
std::vector<T> _data;

View File

@ -294,9 +294,9 @@ void CCBReader::cleanUpNodeGraph(Node *node)
node->setUserObject(nullptr);
auto& children = node->getChildren();
std::for_each(children.begin(), children.end(), [this](Node* obj){
for(const auto &obj : children) {
cleanUpNodeGraph(obj);
});
}
}
Node* CCBReader::readFileWithCleanUp(bool bCleanUp, CCBAnimationManagerMapPtr am)

View File

@ -399,7 +399,7 @@ int ActionNode::getLastFrameIndex()
continue;
}
bFindFrame = true;
int lastInex = cArray->count() - 1;
ssize_t lastInex = cArray->count() - 1;
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(lastInex));
int iFrameIndex = frame->getFrameIndex();
@ -428,7 +428,7 @@ bool ActionNode::updateActionToTimeLine(float fTime)
{
continue;
}
int frameCount = cArray->count();
ssize_t frameCount = cArray->count();
for (int i = 0; i < frameCount; i++)
{
ActionFrame* frame = (ActionFrame*)(cArray->getObjectAtIndex(i));

View File

@ -338,6 +338,22 @@ void Armature::updateOffsetPoint()
}
}
void Armature::setAnchorPoint(const Point& point)
{
if( ! point.equals(_anchorPoint))
{
_anchorPoint = point;
_anchorPointInPoints = Point(_contentSize.width * _anchorPoint.x - _offsetPoint.x, _contentSize.height * _anchorPoint.y - _offsetPoint.y);
_realAnchorPointInPoints = Point(_contentSize.width * _anchorPoint.x, _contentSize.height * _anchorPoint.y);
_transformDirty = _inverseDirty = true;
}
}
const Point& Armature::getAnchorPointInPoints() const
{
return _realAnchorPointInPoints;
}
void Armature::setAnimation(ArmatureAnimation *animation)
{
_animation = animation;
@ -357,9 +373,9 @@ void Armature::update(float dt)
{
_animation->update(dt);
std::for_each(_topBoneList.begin(), _topBoneList.end(), [&dt](Bone* bone){
for(const auto &bone : _topBoneList) {
bone->update(dt);
});
}
_armatureTransformDirty = false;
}
@ -428,11 +444,6 @@ void Armature::visit()
}
kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
transform();
sortAllChildren();
draw();
@ -440,11 +451,6 @@ void Armature::visit()
// reset for next frame
_orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
}
@ -456,7 +462,7 @@ Rect Armature::getBoundingBox() const
Rect boundingBox = Rect(0, 0, 0, 0);
for_each(_children.begin(), _children.end(), [&minx, &miny, &maxx, &maxy, &first, &boundingBox](Node *object)
for (const auto& object : _children)
{
if (Bone *bone = dynamic_cast<Bone *>(object))
{
@ -482,7 +488,7 @@ Rect Armature::getBoundingBox() const
boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
}
});
}
return RectApplyTransform(boundingBox, getNodeToParentTransform());
}
@ -626,15 +632,15 @@ void Armature::setBody(cpBody *body)
_body = body;
_body->data = this;
for (auto& object : _children)
for (const auto& object : _children)
{
if (Bone *bone = dynamic_cast<Bone *>(object))
{
auto displayList = bone->getDisplayManager()->getDecorativeDisplayList();
for_each(displayList.begin(), displayList.end(), [&body](DecorativeDisplay* displayObject)
for (const auto& displayObject : displayList)
{
ColliderDetector *detector = displayObject->getColliderDetector();
auto detector = displayObject->getColliderDetector();
if (detector != nullptr)
{
detector->setBody(body);

View File

@ -178,6 +178,8 @@ public:
* Set contentsize and Calculate anchor point.
*/
virtual void updateOffsetPoint();
virtual void setAnchorPoint(const cocos2d::Point& point) override;
virtual const cocos2d::Point& getAnchorPointInPoints() const override;
virtual void setAnimation(ArmatureAnimation *animation);
virtual ArmatureAnimation *getAnimation() const;
@ -265,6 +267,7 @@ protected:
cocos2d::BlendFunc _blendFunc; //! It's required for CCTextureProtocol inheritance
cocos2d::Point _offsetPoint;
cocos2d::Point _realAnchorPointInPoints;
ArmatureAnimation *_animation;

View File

@ -97,28 +97,28 @@ bool ArmatureAnimation::init(Armature *armature)
void ArmatureAnimation::pause()
{
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween)
for (const auto& tween : _tweenList)
{
tween->pause();
});
}
ProcessBase::pause();
}
void ArmatureAnimation::resume()
{
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween)
for (const auto& tween : _tweenList)
{
tween->resume();
});
}
ProcessBase::resume();
}
void ArmatureAnimation::stop()
{
for_each(_tweenList.begin(), _tweenList.end(), [](Tween *tween)
for (const auto& tween : _tweenList)
{
tween->stop();
});
}
_tweenList.clear();
ProcessBase::stop();
}
@ -308,10 +308,10 @@ void ArmatureAnimation::gotoAndPlay(int frameIndex)
_currentFrame = _nextFrameIndex * _currentPercent;
for_each(_tweenList.begin(), _tweenList.end(), [&frameIndex](Tween* tween)
for (const auto &tween : _tweenList)
{
tween->gotoAndPlay(frameIndex);
});
}
_armature->update(0);
@ -333,10 +333,10 @@ void ArmatureAnimation::update(float dt)
{
ProcessBase::update(dt);
for_each(_tweenList.begin(), _tweenList.end(), [&dt](Tween* tween)
for (const auto &tween : _tweenList)
{
tween->update(dt);
});
}
while (_frameEventQueue.size() > 0)
{

View File

@ -101,11 +101,6 @@ void BatchNode::visit()
}
kmGLPushMatrix();
if (_grid && _grid->isActive())
{
_grid->beforeDraw();
}
transform();
sortAllChildren();
draw();
@ -113,11 +108,6 @@ void BatchNode::visit()
// reset for next frame
_orderOfArrival = 0;
if (_grid && _grid->isActive())
{
_grid->afterDraw(this);
}
kmGLPopMatrix();
}

View File

@ -229,11 +229,10 @@ void Bone::update(float delta)
DisplayFactory::updateDisplay(this, delta, _boneTransformDirty || _armature->getArmatureTransformDirty());
std::for_each(_children.begin(), _children.end(), [&delta](Node* obj)
{
for(const auto &obj: _children) {
Bone *childBone = static_cast<Bone*>(obj);
childBone->update(delta);
});
}
_boneTransformDirty = false;
}

View File

@ -202,28 +202,28 @@ void ColliderDetector::addContourData(ContourData *contourData)
void ColliderDetector::addContourDataList(cocos2d::Vector<ContourData*> &contourDataList)
{
for_each(contourDataList.begin(), contourDataList.end(), [this](ContourData *contourData)
for (const auto &contourData : contourDataList)
{
this->addContourData(contourData);
});
}
}
void ColliderDetector::removeContourData(ContourData *contourData)
{
std::vector<ColliderBody*> eraseList;
for_each(_colliderBodyList.begin(), _colliderBodyList.end(), [&contourData, this, &eraseList](ColliderBody *body)
for (const auto &body : _colliderBodyList)
{
if (body && body->getContourData() == contourData)
{
eraseList.push_back(body);
}
});
}
for_each(eraseList.begin(), eraseList.end(), [this](ColliderBody *body)
for (const auto &body : eraseList)
{
this->_colliderBodyList.eraseObject(body);
});
}
}
void ColliderDetector::removeAll()

View File

@ -24,6 +24,10 @@ SkeletonJson.cpp \
Skin.cpp \
Slot.cpp \
SlotData.cpp \
BoundingBoxAttachment.cpp \
Event.cpp \
EventData.cpp \
SkeletonBounds.cpp \
extension.cpp \
spine-cocos2dx.cpp

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,82 +29,84 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/Animation.h>
#include <math.h>
#include <limits.h>
#include <spine/extension.h>
namespace spine {
Animation* Animation_create (const char* name, int timelineCount) {
Animation* self = NEW(Animation);
spAnimation* spAnimation_create (const char* name, int timelineCount) {
spAnimation* self = NEW(spAnimation);
MALLOC_STR(self->name, name);
self->timelineCount = timelineCount;
self->timelines = MALLOC(Timeline*, timelineCount);
self->timelines = MALLOC(spTimeline*, timelineCount);
return self;
}
void Animation_dispose (Animation* self) {
void spAnimation_dispose (spAnimation* self) {
int i;
for (i = 0; i < self->timelineCount; ++i)
Timeline_dispose(self->timelines[i]);
spTimeline_dispose(self->timelines[i]);
FREE(self->timelines);
FREE(self->name);
FREE(self);
}
void Animation_apply (const Animation* self, Skeleton* skeleton, float time, int/*bool*/loop) {
void spAnimation_apply (const spAnimation* self, spSkeleton* skeleton, float lastTime, float time, int loop, spEvent** events,
int* eventCount) {
int i, n = self->timelineCount;
#ifdef __STDC_VERSION__
if (loop && self->duration) time = fmodf(time, self->duration);
#else
if (loop && self->duration) time = (float)fmod(time, self->duration);
#endif
if (loop && self->duration) {
time = FMOD(time, self->duration);
lastTime = FMOD(lastTime, self->duration);
}
for (i = 0; i < n; ++i)
Timeline_apply(self->timelines[i], skeleton, time, 1);
spTimeline_apply(self->timelines[i], skeleton, lastTime, time, events, eventCount, 1);
}
void Animation_mix (const Animation* self, Skeleton* skeleton, float time, int/*bool*/loop, float alpha) {
void spAnimation_mix (const spAnimation* self, spSkeleton* skeleton, float lastTime, float time, int loop, spEvent** events,
int* eventCount, float alpha) {
int i, n = self->timelineCount;
#ifdef __STDC_VERSION__
if (loop && self->duration) time = fmodf(time, self->duration);
#else
if (loop && self->duration) time = (float)fmod(time, self->duration);
#endif
if (loop && self->duration) {
time = FMOD(time, self->duration);
lastTime = FMOD(lastTime, self->duration);
}
for (i = 0; i < n; ++i)
Timeline_apply(self->timelines[i], skeleton, time, alpha);
spTimeline_apply(self->timelines[i], skeleton, lastTime, time, events, eventCount, alpha);
}
/**/
typedef struct _TimelineVtable {
void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha);
void (*dispose) (Timeline* self);
} _TimelineVtable;
typedef struct _spTimelineVtable {
void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha);
void (*dispose) (spTimeline* self);
} _spTimelineVtable;
void _Timeline_init (Timeline* self, /**/
void (*dispose) (Timeline* self), /**/
void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)) {
CONST_CAST(_TimelineVtable*, self->vtable) = NEW(_TimelineVtable);
VTABLE(Timeline, self) ->dispose = dispose;
VTABLE(Timeline, self) ->apply = apply;
void _spTimeline_init (spTimeline* self, spTimelineType type, /**/
void (*dispose) (spTimeline* self), /**/
void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha)) {
CONST_CAST(spTimelineType, self->type) = type;
CONST_CAST(_spTimelineVtable*, self->vtable) = NEW(_spTimelineVtable);
VTABLE(spTimeline, self)->dispose = dispose;
VTABLE(spTimeline, self)->apply = apply;
}
void _Timeline_deinit (Timeline* self) {
void _spTimeline_deinit (spTimeline* self) {
FREE(self->vtable);
}
void Timeline_dispose (Timeline* self) {
VTABLE(Timeline, self) ->dispose(self);
void spTimeline_dispose (spTimeline* self) {
VTABLE(spTimeline, self)->dispose(self);
}
void Timeline_apply (const Timeline* self, Skeleton* skeleton, float time, float alpha) {
VTABLE(Timeline, self) ->apply(self, skeleton, time, alpha);
void spTimeline_apply (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha) {
VTABLE(spTimeline, self)->apply(self, skeleton, lastTime, time, firedEvents, eventCount, alpha);
}
/**/
@ -105,27 +115,28 @@ static const float CURVE_LINEAR = 0;
static const float CURVE_STEPPED = -1;
static const int CURVE_SEGMENTS = 10;
void _CurveTimeline_init (CurveTimeline* self, int frameCount, /**/
void (*dispose) (Timeline* self), /**/
void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)) {
_Timeline_init(SUPER(self), dispose, apply);
void _spCurveTimeline_init (spCurveTimeline* self, spTimelineType type, int frameCount, /**/
void (*dispose) (spTimeline* self), /**/
void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha)) {
_spTimeline_init(SUPER(self), type, dispose, apply);
self->curves = CALLOC(float, (frameCount - 1) * 6);
}
void _CurveTimeline_deinit (CurveTimeline* self) {
_Timeline_deinit(SUPER(self));
void _spCurveTimeline_deinit (spCurveTimeline* self) {
_spTimeline_deinit(SUPER(self));
FREE(self->curves);
}
void CurveTimeline_setLinear (CurveTimeline* self, int frameIndex) {
void spCurveTimeline_setLinear (spCurveTimeline* self, int frameIndex) {
self->curves[frameIndex * 6] = CURVE_LINEAR;
}
void CurveTimeline_setStepped (CurveTimeline* self, int frameIndex) {
void spCurveTimeline_setStepped (spCurveTimeline* self, int frameIndex) {
self->curves[frameIndex * 6] = CURVE_STEPPED;
}
void CurveTimeline_setCurve (CurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2) {
void spCurveTimeline_setCurve (spCurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2) {
float subdiv_step = 1.0f / CURVE_SEGMENTS;
float subdiv_step2 = subdiv_step * subdiv_step;
float subdiv_step3 = subdiv_step2 * subdiv_step;
@ -146,7 +157,7 @@ void CurveTimeline_setCurve (CurveTimeline* self, int frameIndex, float cx1, flo
self->curves[i + 5] = tmp2y * pre5;
}
float CurveTimeline_getCurvePercent (const CurveTimeline* self, int frameIndex, float percent) {
float spCurveTimeline_getCurvePercent (const spCurveTimeline* self, int frameIndex, float percent) {
float dfy;
float ddfx;
float ddfy;
@ -211,19 +222,19 @@ static int binarySearch (float *values, int valuesLength, float target, int step
/**/
void _BaseTimeline_dispose (Timeline* timeline) {
struct BaseTimeline* self = SUB_CAST(struct BaseTimeline, timeline);
_CurveTimeline_deinit(SUPER(self));
void _spBaseTimeline_dispose (spTimeline* timeline) {
struct spBaseTimeline* self = SUB_CAST(struct spBaseTimeline, timeline);
_spCurveTimeline_deinit(SUPER(self));
FREE(self->frames);
FREE(self);
}
/* Many timelines have structure identical to struct BaseTimeline and extend CurveTimeline. **/
struct BaseTimeline* _BaseTimeline_create (int frameCount, int frameSize, /**/
void (*apply) (const Timeline* self, Skeleton* skeleton, float time, float alpha)) {
struct BaseTimeline* self = NEW(struct BaseTimeline);
_CurveTimeline_init(SUPER(self), frameCount, _BaseTimeline_dispose, apply);
/* Many timelines have structure identical to struct spBaseTimeline and extend spCurveTimeline. **/
struct spBaseTimeline* _spBaseTimeline_create (int frameCount, spTimelineType type, int frameSize, /**/
void (*apply) (const spTimeline* self, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha)) {
struct spBaseTimeline* self = NEW(struct spBaseTimeline);
_spCurveTimeline_init(SUPER(self), type, frameCount, _spBaseTimeline_dispose, apply);
CONST_CAST(int, self->framesLength) = frameCount * frameSize;
CONST_CAST(float*, self->frames) = CALLOC(float, self->framesLength);
@ -236,24 +247,25 @@ struct BaseTimeline* _BaseTimeline_create (int frameCount, int frameSize, /**/
static const int ROTATE_LAST_FRAME_TIME = -2;
static const int ROTATE_FRAME_VALUE = 1;
void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float time, float alpha) {
Bone *bone;
void _spRotateTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha) {
spBone *bone;
int frameIndex;
float lastFrameValue, frameTime, percent, amount;
RotateTimeline* self = SUB_CAST(RotateTimeline, timeline);
spRotateTimeline* self = SUB_CAST(spRotateTimeline, timeline);
if (time < self->frames[0]) return; /* Time is before first frame. */
bone = skeleton->bones[self->boneIndex];
if (time >= self->frames[self->framesLength - 2]) { /* Time is after last frame. */
float count = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation;
while (count > 180)
count -= 360;
while (count < -180)
count += 360;
bone->rotation += count * alpha;
float amount = bone->data->rotation + self->frames[self->framesLength - 1] - bone->rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone->rotation += amount * alpha;
return;
}
@ -262,7 +274,7 @@ void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float
lastFrameValue = self->frames[frameIndex - 1];
frameTime = self->frames[frameIndex];
percent = 1 - (time - frameTime) / (self->frames[frameIndex + ROTATE_LAST_FRAME_TIME] - frameTime);
percent = CurveTimeline_getCurvePercent(SUPER(self), frameIndex / 2 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 2 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
amount = self->frames[frameIndex + ROTATE_FRAME_VALUE] - lastFrameValue;
while (amount > 180)
@ -277,11 +289,11 @@ void _RotateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float
bone->rotation += amount * alpha;
}
RotateTimeline* RotateTimeline_create (int frameCount) {
return _BaseTimeline_create(frameCount, 2, _RotateTimeline_apply);
spRotateTimeline* spRotateTimeline_create (int frameCount) {
return _spBaseTimeline_create(frameCount, TIMELINE_ROTATE, 2, _spRotateTimeline_apply);
}
void RotateTimeline_setFrame (RotateTimeline* self, int frameIndex, float time, float angle) {
void spRotateTimeline_setFrame (spRotateTimeline* self, int frameIndex, float time, float angle) {
frameIndex *= 2;
self->frames[frameIndex] = time;
self->frames[frameIndex + 1] = angle;
@ -293,12 +305,13 @@ static const int TRANSLATE_LAST_FRAME_TIME = -3;
static const int TRANSLATE_FRAME_X = 1;
static const int TRANSLATE_FRAME_Y = 2;
void _TranslateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float time, float alpha) {
Bone *bone;
void _spTranslateTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
spEvent** firedEvents, int* eventCount, float alpha) {
spBone *bone;
int frameIndex;
float lastFrameX, lastFrameY, frameTime, percent;
TranslateTimeline* self = SUB_CAST(TranslateTimeline, timeline);
spTranslateTimeline* self = SUB_CAST(spTranslateTimeline, timeline);
if (time < self->frames[0]) return; /* Time is before first frame. */
@ -316,7 +329,7 @@ void _TranslateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, flo
lastFrameY = self->frames[frameIndex - 1];
frameTime = self->frames[frameIndex];
percent = 1 - (time - frameTime) / (self->frames[frameIndex + TRANSLATE_LAST_FRAME_TIME] - frameTime);
percent = CurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
bone->x += (bone->data->x + lastFrameX + (self->frames[frameIndex + TRANSLATE_FRAME_X] - lastFrameX) * percent - bone->x)
* alpha;
@ -324,11 +337,11 @@ void _TranslateTimeline_apply (const Timeline* timeline, Skeleton* skeleton, flo
* alpha;
}
TranslateTimeline* TranslateTimeline_create (int frameCount) {
return _BaseTimeline_create(frameCount, 3, _TranslateTimeline_apply);
spTranslateTimeline* spTranslateTimeline_create (int frameCount) {
return _spBaseTimeline_create(frameCount, TIMELINE_TRANLATE, 3, _spTranslateTimeline_apply);
}
void TranslateTimeline_setFrame (TranslateTimeline* self, int frameIndex, float time, float x, float y) {
void spTranslateTimeline_setFrame (spTranslateTimeline* self, int frameIndex, float time, float x, float y) {
frameIndex *= 3;
self->frames[frameIndex] = time;
self->frames[frameIndex + 1] = x;
@ -337,13 +350,14 @@ void TranslateTimeline_setFrame (TranslateTimeline* self, int frameIndex, float
/**/
void _ScaleTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float time, float alpha) {
Bone *bone;
void _spScaleTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha) {
spBone *bone;
int frameIndex;
float lastFrameX, lastFrameY, frameTime, percent;
ScaleTimeline* self = SUB_CAST(ScaleTimeline, timeline);
spScaleTimeline* self = SUB_CAST(spScaleTimeline, timeline);
if (time < self->frames[0]) return; /* Time is before first frame. */
bone = skeleton->bones[self->boneIndex];
@ -359,7 +373,7 @@ void _ScaleTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float t
lastFrameY = self->frames[frameIndex - 1];
frameTime = self->frames[frameIndex];
percent = 1 - (time - frameTime) / (self->frames[frameIndex + TRANSLATE_LAST_FRAME_TIME] - frameTime);
percent = CurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
bone->scaleX += (bone->data->scaleX - 1 + lastFrameX + (self->frames[frameIndex + TRANSLATE_FRAME_X] - lastFrameX) * percent
- bone->scaleX) * alpha;
@ -367,12 +381,12 @@ void _ScaleTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float t
- bone->scaleY) * alpha;
}
ScaleTimeline* ScaleTimeline_create (int frameCount) {
return _BaseTimeline_create(frameCount, 3, _ScaleTimeline_apply);
spScaleTimeline* spScaleTimeline_create (int frameCount) {
return _spBaseTimeline_create(frameCount, TIMELINE_SCALE, 3, _spScaleTimeline_apply);
}
void ScaleTimeline_setFrame (ScaleTimeline* self, int frameIndex, float time, float x, float y) {
TranslateTimeline_setFrame(self, frameIndex, time, x, y);
void spScaleTimeline_setFrame (spScaleTimeline* self, int frameIndex, float time, float x, float y) {
spTranslateTimeline_setFrame(self, frameIndex, time, x, y);
}
/**/
@ -383,12 +397,13 @@ static const int COLOR_FRAME_G = 2;
static const int COLOR_FRAME_B = 3;
static const int COLOR_FRAME_A = 4;
void _ColorTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float time, float alpha) {
Slot *slot;
void _spColorTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha) {
spSlot *slot;
int frameIndex;
float lastFrameR, lastFrameG, lastFrameB, lastFrameA, percent, frameTime;
float r, g, b, a;
ColorTimeline* self = (ColorTimeline*)timeline;
spColorTimeline* self = (spColorTimeline*)timeline;
if (time < self->frames[0]) return; /* Time is before first frame. */
@ -411,7 +426,7 @@ void _ColorTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float t
lastFrameA = self->frames[frameIndex - 1];
frameTime = self->frames[frameIndex];
percent = 1 - (time - frameTime) / (self->frames[frameIndex + COLOR_LAST_FRAME_TIME] - frameTime);
percent = CurveTimeline_getCurvePercent(SUPER(self), frameIndex / 5 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
percent = spCurveTimeline_getCurvePercent(SUPER(self), frameIndex / 5 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
r = lastFrameR + (self->frames[frameIndex + COLOR_FRAME_R] - lastFrameR) * percent;
g = lastFrameG + (self->frames[frameIndex + COLOR_FRAME_G] - lastFrameG) * percent;
@ -430,11 +445,11 @@ void _ColorTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float t
}
}
ColorTimeline* ColorTimeline_create (int frameCount) {
return (ColorTimeline*)_BaseTimeline_create(frameCount, 5, _ColorTimeline_apply);
spColorTimeline* spColorTimeline_create (int frameCount) {
return (spColorTimeline*)_spBaseTimeline_create(frameCount, TIMELINE_COLOR, 5, _spColorTimeline_apply);
}
void ColorTimeline_setFrame (ColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a) {
void spColorTimeline_setFrame (spColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a) {
frameIndex *= 5;
self->frames[frameIndex] = time;
self->frames[frameIndex + 1] = r;
@ -445,10 +460,11 @@ void ColorTimeline_setFrame (ColorTimeline* self, int frameIndex, float time, fl
/**/
void _AttachmentTimeline_apply (const Timeline* timeline, Skeleton* skeleton, float time, float alpha) {
void _spAttachmentTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
spEvent** firedEvents, int* eventCount, float alpha) {
int frameIndex;
const char* attachmentName;
AttachmentTimeline* self = (AttachmentTimeline*)timeline;
spAttachmentTimeline* self = (spAttachmentTimeline*)timeline;
if (time < self->frames[0]) return; /* Time is before first frame. */
@ -458,16 +474,15 @@ void _AttachmentTimeline_apply (const Timeline* timeline, Skeleton* skeleton, fl
frameIndex = binarySearch(self->frames, self->framesLength, time, 1) - 1;
attachmentName = self->attachmentNames[frameIndex];
Slot_setAttachment(skeleton->slots[self->slotIndex],
attachmentName ? Skeleton_getAttachmentForSlotIndex(skeleton, self->slotIndex, attachmentName) : 0);
spSlot_setAttachment(skeleton->slots[self->slotIndex],
attachmentName ? spSkeleton_getAttachmentForSlotIndex(skeleton, self->slotIndex, attachmentName) : 0);
}
void _AttachmentTimeline_dispose (Timeline* timeline) {
AttachmentTimeline* self;
void _spAttachmentTimeline_dispose (spTimeline* timeline) {
spAttachmentTimeline* self = SUB_CAST(spAttachmentTimeline, timeline);
int i;
_Timeline_deinit(timeline);
self = (AttachmentTimeline*)timeline;
_spTimeline_deinit(timeline);
for (i = 0; i < self->framesLength; ++i)
FREE(self->attachmentNames[i]);
@ -476,19 +491,20 @@ void _AttachmentTimeline_dispose (Timeline* timeline) {
FREE(self);
}
AttachmentTimeline* AttachmentTimeline_create (int frameCount) {
AttachmentTimeline* self = NEW(AttachmentTimeline);
_Timeline_init(SUPER(self), _AttachmentTimeline_dispose, _AttachmentTimeline_apply);
spAttachmentTimeline* spAttachmentTimeline_create (int frameCount) {
spAttachmentTimeline* self = NEW(spAttachmentTimeline);
_spTimeline_init(SUPER(self), TIMELINE_ATTACHMENT, _spAttachmentTimeline_dispose, _spAttachmentTimeline_apply);
CONST_CAST(char**, self->attachmentNames) = CALLOC(char*, frameCount);
CONST_CAST(int, self->framesLength) = frameCount;
CONST_CAST(float*, self->frames) = CALLOC(float, frameCount);
CONST_CAST(char**, self->attachmentNames) = CALLOC(char*, frameCount);
return self;
}
void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, float time, const char* attachmentName) {
void spAttachmentTimeline_setFrame (spAttachmentTimeline* self, int frameIndex, float time, const char* attachmentName) {
self->frames[frameIndex] = time;
FREE(self->attachmentNames[frameIndex]);
if (attachmentName)
MALLOC_STR(self->attachmentNames[frameIndex], attachmentName);
@ -496,4 +512,128 @@ void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, floa
self->attachmentNames[frameIndex] = 0;
}
} // namespace spine {
/**/
/** Fires events for frames > lastTime and <= time. */
void _spEventTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha) {
spEventTimeline* self = (spEventTimeline*)timeline;
int frameIndex;
if (!firedEvents) return;
if (lastTime > time) { /* Fire events after last time for looped animations. */
_spEventTimeline_apply(timeline, skeleton, lastTime, (float)INT_MAX, firedEvents, eventCount, alpha);
lastTime = -1;
} else if (lastTime >= self->frames[self->framesLength - 1]) /* Last time is after last frame. */
return;
if (time < self->frames[0]) return; /* Time is before first frame. */
if (lastTime < self->frames[0])
frameIndex = 0;
else {
float frame;
frameIndex = binarySearch(self->frames, self->framesLength, lastTime, 1);
frame = self->frames[frameIndex];
while (frameIndex > 0) { /* Fire multiple events with the same frame. */
if (self->frames[frameIndex - 1] != frame) break;
frameIndex--;
}
}
for (; frameIndex < self->framesLength && time >= self->frames[frameIndex]; frameIndex++) {
firedEvents[*eventCount] = self->events[frameIndex];
(*eventCount)++;
}
}
void _spEventTimeline_dispose (spTimeline* timeline) {
spEventTimeline* self = SUB_CAST(spEventTimeline, timeline);
int i;
_spTimeline_deinit(timeline);
for (i = 0; i < self->framesLength; ++i)
spEvent_dispose(self->events[i]);
FREE(self->events);
FREE(self->frames);
FREE(self);
}
spEventTimeline* spEventTimeline_create (int frameCount) {
spEventTimeline* self = NEW(spEventTimeline);
_spTimeline_init(SUPER(self), TIMELINE_EVENT, _spEventTimeline_dispose, _spEventTimeline_apply);
CONST_CAST(int, self->framesLength) = frameCount;
CONST_CAST(float*, self->frames) = CALLOC(float, frameCount);
CONST_CAST(spEvent**, self->events) = CALLOC(spEvent*, frameCount);
return self;
}
void spEventTimeline_setFrame (spEventTimeline* self, int frameIndex, float time, spEvent* event) {
self->frames[frameIndex] = time;
FREE(self->events[frameIndex]);
self->events[frameIndex] = event;
}
/**/
void _spDrawOrderTimeline_apply (const spTimeline* timeline, spSkeleton* skeleton, float lastTime, float time,
spEvent** firedEvents, int* eventCount, float alpha) {
int i;
int frameIndex;
const int* drawOrderToSetupIndex;
spDrawOrderTimeline* self = (spDrawOrderTimeline*)timeline;
if (time < self->frames[0]) return; /* Time is before first frame. */
if (time >= self->frames[self->framesLength - 1]) /* Time is after last frame. */
frameIndex = self->framesLength - 1;
else
frameIndex = binarySearch(self->frames, self->framesLength, time, 1) - 1;
drawOrderToSetupIndex = self->drawOrders[frameIndex];
if (!drawOrderToSetupIndex)
memcpy(skeleton->drawOrder, skeleton->slots, self->slotCount * sizeof(int));
else {
for (i = 0; i < self->slotCount; i++)
skeleton->drawOrder[i] = skeleton->slots[drawOrderToSetupIndex[i]];
}
}
void _spDrawOrderTimeline_dispose (spTimeline* timeline) {
spDrawOrderTimeline* self = SUB_CAST(spDrawOrderTimeline, timeline);
int i;
_spTimeline_deinit(timeline);
for (i = 0; i < self->framesLength; ++i)
FREE(self->drawOrders[i]);
FREE(self->drawOrders);
FREE(self->frames);
FREE(self);
}
spDrawOrderTimeline* spDrawOrderTimeline_create (int frameCount, int slotCount) {
spDrawOrderTimeline* self = NEW(spDrawOrderTimeline);
_spTimeline_init(SUPER(self), TIMELINE_DRAWORDER, _spDrawOrderTimeline_dispose, _spDrawOrderTimeline_apply);
CONST_CAST(int, self->framesLength) = frameCount;
CONST_CAST(float*, self->frames) = CALLOC(float, frameCount);
CONST_CAST(int**, self->drawOrders) = CALLOC(int*, frameCount);
CONST_CAST(int, self->slotCount) = slotCount;
return self;
}
void spDrawOrderTimeline_setFrame (spDrawOrderTimeline* self, int frameIndex, float time, const int* drawOrder) {
self->frames[frameIndex] = time;
FREE(self->drawOrders[frameIndex]);
if (!drawOrder)
self->drawOrders[frameIndex] = 0;
else {
self->drawOrders[frameIndex] = MALLOC(int, self->slotCount);
memcpy(CONST_CAST(int*, self->drawOrders[frameIndex]), drawOrder, self->slotCount * sizeof(int));
}
}

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,112 +29,226 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ANIMATION_H_
#define SPINE_ANIMATION_H_
namespace spine {
#include <spine/Event.h>
typedef struct Timeline Timeline;
struct Skeleton;
#ifdef __cplusplus
extern "C" {
#endif
typedef struct spTimeline spTimeline;
struct spSkeleton;
typedef struct {
const char* const name;
float duration;
int timelineCount;
Timeline** timelines;
} Animation;
spTimeline** timelines;
} spAnimation;
Animation* Animation_create (const char* name, int timelineCount);
void Animation_dispose (Animation* self);
spAnimation* spAnimation_create (const char* name, int timelineCount);
void spAnimation_dispose (spAnimation* self);
void Animation_apply (const Animation* self, struct Skeleton* skeleton, float time, int/*bool*/loop);
void Animation_mix (const Animation* self, struct Skeleton* skeleton, float time, int/*bool*/loop, float alpha);
/** Poses the skeleton at the specified time for this animation.
* @param lastTime The last time the animation was applied.
* @param events Any triggered events are added. */
void spAnimation_apply (const spAnimation* self, struct spSkeleton* skeleton, float lastTime, float time, int loop,
spEvent** events, int* eventCount);
/** Poses the skeleton at the specified time for this animation mixed with the current pose.
* @param lastTime The last time the animation was applied.
* @param events Any triggered events are added.
* @param alpha The amount of this animation that affects the current pose. */
void spAnimation_mix (const spAnimation* self, struct spSkeleton* skeleton, float lastTime, float time, int loop,
spEvent** events, int* eventCount, float alpha);
#ifdef SPINE_SHORT_NAMES
typedef spAnimation Animation;
#define Animation_create(...) spAnimation_create(__VA_ARGS__)
#define Animation_dispose(...) spAnimation_dispose(__VA_ARGS__)
#define Animation_apply(...) spAnimation_apply(__VA_ARGS__)
#define Animation_mix(...) spAnimation_mix(__VA_ARGS__)
#endif
/**/
struct Timeline {
typedef enum {
TIMELINE_SCALE, TIMELINE_ROTATE, TIMELINE_TRANLATE, TIMELINE_COLOR, TIMELINE_ATTACHMENT, TIMELINE_EVENT, TIMELINE_DRAWORDER
} spTimelineType;
struct spTimeline {
const spTimelineType type;
const void* const vtable;
};
void Timeline_dispose (Timeline* self);
void Timeline_apply (const Timeline* self, struct Skeleton* skeleton, float time, float alpha);
void spTimeline_dispose (spTimeline* self);
void spTimeline_apply (const spTimeline* self, struct spSkeleton* skeleton, float lastTime, float time, spEvent** firedEvents,
int* eventCount, float alpha);
#ifdef SPINE_SHORT_NAMES
typedef spTimeline Timeline;
#define Timeline_dispose(...) spTimeline_dispose(__VA_ARGS__)
#define Timeline_apply(...) spTimeline_apply(__VA_ARGS__)
#endif
/**/
typedef struct {
Timeline super;
spTimeline super;
float* curves; /* dfx, dfy, ddfx, ddfy, dddfx, dddfy, ... */
} CurveTimeline;
} spCurveTimeline;
void CurveTimeline_setLinear (CurveTimeline* self, int frameIndex);
void CurveTimeline_setStepped (CurveTimeline* self, int frameIndex);
void spCurveTimeline_setLinear (spCurveTimeline* self, int frameIndex);
void spCurveTimeline_setStepped (spCurveTimeline* self, int frameIndex);
/* Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
* cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
* the difference between the keyframe's values. */
void CurveTimeline_setCurve (CurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2);
float CurveTimeline_getCurvePercent (const CurveTimeline* self, int frameIndex, float percent);
void spCurveTimeline_setCurve (spCurveTimeline* self, int frameIndex, float cx1, float cy1, float cx2, float cy2);
float spCurveTimeline_getCurvePercent (const spCurveTimeline* self, int frameIndex, float percent);
#ifdef SPINE_SHORT_NAMES
typedef spCurveTimeline CurveTimeline;
#define CurveTimeline_setLinear(...) spCurveTimeline_setLinear(__VA_ARGS__)
#define CurveTimeline_setStepped(...) spCurveTimeline_setStepped(__VA_ARGS__)
#define CurveTimeline_setCurve(...) spCurveTimeline_setCurve(__VA_ARGS__)
#define CurveTimeline_getCurvePercent(...) spCurveTimeline_getCurvePercent(__VA_ARGS__)
#endif
/**/
typedef struct BaseTimeline {
CurveTimeline super;
typedef struct spBaseTimeline {
spCurveTimeline super;
int const framesLength;
float* const frames; /* time, angle, ... for rotate. time, x, y, ... for translate and scale. */
int boneIndex;
} RotateTimeline;
} spRotateTimeline;
RotateTimeline* RotateTimeline_create (int frameCount);
spRotateTimeline* spRotateTimeline_create (int frameCount);
void RotateTimeline_setFrame (RotateTimeline* self, int frameIndex, float time, float angle);
void spRotateTimeline_setFrame (spRotateTimeline* self, int frameIndex, float time, float angle);
#ifdef SPINE_SHORT_NAMES
typedef spRotateTimeline RotateTimeline;
#define RotateTimeline_create(...) spRotateTimeline_create(__VA_ARGS__)
#define RotateTimeline_setFrame(...) spRotateTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct BaseTimeline TranslateTimeline;
typedef struct spBaseTimeline spTranslateTimeline;
TranslateTimeline* TranslateTimeline_create (int frameCount);
spTranslateTimeline* spTranslateTimeline_create (int frameCount);
void TranslateTimeline_setFrame (TranslateTimeline* self, int frameIndex, float time, float x, float y);
void spTranslateTimeline_setFrame (spTranslateTimeline* self, int frameIndex, float time, float x, float y);
#ifdef SPINE_SHORT_NAMES
typedef spTranslateTimeline TranslateTimeline;
#define TranslateTimeline_create(...) spTranslateTimeline_create(__VA_ARGS__)
#define TranslateTimeline_setFrame(...) spTranslateTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct BaseTimeline ScaleTimeline;
typedef struct spBaseTimeline spScaleTimeline;
ScaleTimeline* ScaleTimeline_create (int frameCount);
spScaleTimeline* spScaleTimeline_create (int frameCount);
void ScaleTimeline_setFrame (ScaleTimeline* self, int frameIndex, float time, float x, float y);
void spScaleTimeline_setFrame (spScaleTimeline* self, int frameIndex, float time, float x, float y);
#ifdef SPINE_SHORT_NAMES
typedef spScaleTimeline ScaleTimeline;
#define ScaleTimeline_create(...) spScaleTimeline_create(__VA_ARGS__)
#define ScaleTimeline_setFrame(...) spScaleTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct {
CurveTimeline super;
spCurveTimeline super;
int const framesLength;
float* const frames; /* time, r, g, b, a, ... */
int slotIndex;
} ColorTimeline;
} spColorTimeline;
ColorTimeline* ColorTimeline_create (int frameCount);
spColorTimeline* spColorTimeline_create (int frameCount);
void ColorTimeline_setFrame (ColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a);
void spColorTimeline_setFrame (spColorTimeline* self, int frameIndex, float time, float r, float g, float b, float a);
#ifdef SPINE_SHORT_NAMES
typedef spColorTimeline ColorTimeline;
#define ColorTimeline_create(...) spColorTimeline_create(__VA_ARGS__)
#define ColorTimeline_setFrame(...) spColorTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct {
Timeline super;
spTimeline super;
int const framesLength;
float* const frames; /* time, ... */
int slotIndex;
const char** const attachmentNames;
} AttachmentTimeline;
} spAttachmentTimeline;
AttachmentTimeline* AttachmentTimeline_create (int frameCount);
spAttachmentTimeline* spAttachmentTimeline_create (int frameCount);
/* @param attachmentName May be 0. */
void AttachmentTimeline_setFrame (AttachmentTimeline* self, int frameIndex, float time, const char* attachmentName);
void spAttachmentTimeline_setFrame (spAttachmentTimeline* self, int frameIndex, float time, const char* attachmentName);
#ifdef SPINE_SHORT_NAMES
typedef spAttachmentTimeline AttachmentTimeline;
#define AttachmentTimeline_create(...) spAttachmentTimeline_create(__VA_ARGS__)
#define AttachmentTimeline_setFrame(...) spAttachmentTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct {
spTimeline super;
int const framesLength;
float* const frames; /* time, ... */
spEvent** const events;
} spEventTimeline;
spEventTimeline* spEventTimeline_create (int frameCount);
void spEventTimeline_setFrame (spEventTimeline* self, int frameIndex, float time, spEvent* event);
#ifdef SPINE_SHORT_NAMES
typedef spEventTimeline EventTimeline;
#define EventTimeline_create(...) spEventTimeline_create(__VA_ARGS__)
#define EventTimeline_setFrame(...) spEventTimeline_setFrame(__VA_ARGS__)
#endif
/**/
typedef struct {
spTimeline super;
int const framesLength;
float* const frames; /* time, ... */
const int** const drawOrders;
int const slotCount;
} spDrawOrderTimeline;
spDrawOrderTimeline* spDrawOrderTimeline_create (int frameCount, int slotCount);
void spDrawOrderTimeline_setFrame (spDrawOrderTimeline* self, int frameIndex, float time, const int* drawOrder);
#ifdef SPINE_SHORT_NAMES
typedef spDrawOrderTimeline DrawOrderTimeline;
#define DrawOrderTimeline_create(...) spDrawOrderTimeline_create(__VA_ARGS__)
#define DrawOrderTimeline_setFrame(...) spDrawOrderTimeline_setFrame(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ANIMATION_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,158 +29,254 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/Animation.h>
#include <spine/AnimationState.h>
#include <spine/AnimationStateData.h>
#include <spine/Event.h>
#include <spine/extension.h>
#include <stdio.h>
#include <spine/Skeleton.h>
#include <spine/SkeletonData.h>
#include <string.h>
namespace spine {
spTrackEntry* _spTrackEntry_create () {
spTrackEntry* entry = NEW(spTrackEntry);
entry->timeScale = 1;
entry->lastTime = -1;
return entry;
}
typedef struct _Entry _Entry;
struct _Entry {
Animation* animation;
int/*bool*/loop;
float delay;
_Entry* next;
};
void _spTrackEntry_dispose (spTrackEntry* entry) {
FREE(entry);
}
void _spTrackEntry_disposeAll (spTrackEntry* entry) {
while (entry) {
spTrackEntry* next = entry->next;
_spTrackEntry_dispose(entry);
entry = next;
}
}
/**/
typedef struct {
AnimationState super;
Animation *previous;
float previousTime;
int/*bool*/previousLoop;
float mixTime;
float mixDuration;
_Entry* queue;
} _Internal;
spAnimationState super;
spEvent** events;
} _spAnimationState;
AnimationState* AnimationState_create (AnimationStateData* data) {
AnimationState* self = SUPER(NEW(_Internal));
CONST_CAST(AnimationStateData*, self->data) = data;
void _spAnimationState_setCurrent (spAnimationState* self, int index, spTrackEntry* entry);
spAnimationState* spAnimationState_create (spAnimationStateData* data) {
_spAnimationState* internal = NEW(_spAnimationState);
spAnimationState* self = SUPER(internal);
internal->events = MALLOC(spEvent*, 64);
self->timeScale = 1;
CONST_CAST(spAnimationStateData*, self->data) = data;
return self;
}
void _AnimationState_clearQueue (AnimationState* self) {
_Internal* internal = SUB_CAST(_Internal, self);
_Entry* entry = internal->queue;
while (entry) {
_Entry* nextEntry = entry->next;
FREE(entry);
entry = nextEntry;
}
internal->queue = 0;
}
void AnimationState_dispose (AnimationState* self) {
_AnimationState_clearQueue(self);
void spAnimationState_dispose (spAnimationState* self) {
int i;
_spAnimationState* internal = SUB_CAST(_spAnimationState, self);
FREE(internal->events);
for (i = 0; i < self->trackCount; i++)
_spTrackEntry_disposeAll(self->tracks[i]);
FREE(self->tracks);
FREE(self);
}
void AnimationState_addAnimation (AnimationState* self, Animation* animation, int/*bool*/loop, float delay) {
_Entry* existingEntry;
Animation* previousAnimation;
void spAnimationState_update (spAnimationState* self, float delta) {
int i;
float trackDelta;
delta *= self->timeScale;
for (i = 0; i < self->trackCount; i++) {
spTrackEntry* current = self->tracks[i];
if (!current) continue;
_Internal* internal = SUB_CAST(_Internal, self);
_Entry* entry = NEW(_Entry);
entry->animation = animation;
entry->loop = loop;
trackDelta = delta * current->timeScale;
current->time += trackDelta;
if (current->previous) {
current->previous->time += trackDelta;
current->mixTime += trackDelta;
}
existingEntry = internal->queue;
if (existingEntry) {
while (existingEntry->next)
existingEntry = existingEntry->next;
existingEntry->next = entry;
previousAnimation = existingEntry->animation;
} else {
internal->queue = entry;
previousAnimation = self->animation;
if (current->next) {
if (current->lastTime >= current->next->delay) _spAnimationState_setCurrent(self, i, current->next);
} else {
/* End non-looping animation when it reaches its end time and there is no next entry. */
if (!current->loop && current->lastTime >= current->endTime) spAnimationState_clearTrack(self, i);
}
}
}
void spAnimationState_apply (spAnimationState* self, spSkeleton* skeleton) {
_spAnimationState* internal = SUB_CAST(_spAnimationState, self);
int i, ii;
int eventCount;
float time;
spTrackEntry* previous;
for (i = 0; i < self->trackCount; i++) {
spTrackEntry* current = self->tracks[i];
if (!current) continue;
eventCount = 0;
time = current->time;
if (!current->loop && time > current->endTime) time = current->endTime;
previous = current->previous;
if (!previous) {
spAnimation_apply(current->animation, skeleton, current->lastTime, time, current->loop, internal->events, &eventCount);
} else {
float alpha = current->mixTime / current->mixDuration;
float previousTime = previous->time;
if (!previous->loop && previousTime > previous->endTime) previousTime = previous->endTime;
spAnimation_apply(previous->animation, skeleton, previousTime, previousTime, previous->loop, 0, 0);
if (alpha >= 1) {
alpha = 1;
_spTrackEntry_dispose(current->previous);
current->previous = 0;
}
spAnimation_mix(current->animation, skeleton, current->lastTime, time, current->loop, internal->events, &eventCount,
alpha);
}
for (ii = 0; ii < eventCount; ii++) {
spEvent* event = internal->events[ii];
if (current->listener) current->listener(self, i, ANIMATION_EVENT, event, 0);
if (self->listener) self->listener(self, i, ANIMATION_EVENT, event, 0);
}
/* Check if completed the animation or a loop iteration. */
if (current->loop ? (FMOD(current->lastTime, current->endTime) > FMOD(time, current->endTime)) //
: (current->lastTime < current->endTime && time >= current->endTime)) {
int count = (int)(time / current->endTime);
if (current->listener) current->listener(self, i, ANIMATION_COMPLETE, 0, count);
if (self->listener) self->listener(self, i, ANIMATION_COMPLETE, 0, count);
if (i >= self->trackCount || self->tracks[i] != current) continue;
}
if (i >= self->trackCount || self->tracks[i] != current) continue;
current->lastTime = current->time;
}
}
void spAnimationState_clearTracks (spAnimationState* self) {
int i;
for (i = 0; i < self->trackCount; i++)
spAnimationState_clearTrack(self, i);
self->trackCount = 0;
}
void spAnimationState_clearTrack (spAnimationState* self, int trackIndex) {
spTrackEntry* current;
if (trackIndex >= self->trackCount) return;
current = self->tracks[trackIndex];
if (!current) return;
if (current->listener) current->listener(self, trackIndex, ANIMATION_END, 0, 0);
if (self->listener) self->listener(self, trackIndex, ANIMATION_END, 0, 0);
self->tracks[trackIndex] = 0;
if (current->previous) _spTrackEntry_dispose(current->previous);
_spTrackEntry_disposeAll(current);
}
spTrackEntry* _spAnimationState_expandToIndex (spAnimationState* self, int index) {
spTrackEntry** newTracks;
if (index < self->trackCount) return self->tracks[index];
newTracks = CALLOC(spTrackEntry*, index + 1);
memcpy(newTracks, self->tracks, self->trackCount * sizeof(spTrackEntry*));
FREE(self->tracks);
self->tracks = newTracks;
self->trackCount = index + 1;
return 0;
}
void _spAnimationState_setCurrent (spAnimationState* self, int index, spTrackEntry* entry) {
spTrackEntry* current = _spAnimationState_expandToIndex(self, index);
if (current) {
if (current->previous) {
_spTrackEntry_dispose(current->previous);
current->previous = 0;
}
if (current->listener) current->listener(self, index, ANIMATION_END, 0, 0);
if (self->listener) self->listener(self, index, ANIMATION_END, 0, 0);
entry->mixDuration = spAnimationStateData_getMix(self->data, current->animation, entry->animation);
if (entry->mixDuration > 0) {
entry->mixTime = 0;
entry->previous = current;
} else
_spTrackEntry_dispose(current);
}
self->tracks[index] = entry;
if (entry->listener) current->listener(self, index, ANIMATION_START, 0, 0);
if (self->listener) self->listener(self, index, ANIMATION_START, 0, 0);
}
spTrackEntry* spAnimationState_setAnimationByName (spAnimationState* self, int trackIndex, const char* animationName,
int/*bool*/loop) {
spAnimation* animation = spSkeletonData_findAnimation(self->data->skeletonData, animationName);
return spAnimationState_setAnimation(self, trackIndex, animation, loop);
}
spTrackEntry* spAnimationState_setAnimation (spAnimationState* self, int trackIndex, spAnimation* animation, int/*bool*/loop) {
spTrackEntry* entry;
spTrackEntry* current = _spAnimationState_expandToIndex(self, trackIndex);
if (current) _spTrackEntry_disposeAll(current->next);
entry = _spTrackEntry_create();
entry->animation = animation;
entry->loop = loop;
entry->endTime = animation->duration;
_spAnimationState_setCurrent(self, trackIndex, entry);
return entry;
}
spTrackEntry* spAnimationState_addAnimationByName (spAnimationState* self, int trackIndex, const char* animationName,
int/*bool*/loop, float delay) {
spAnimation* animation = spSkeletonData_findAnimation(self->data->skeletonData, animationName);
return spAnimationState_addAnimation(self, trackIndex, animation, loop, delay);
}
spTrackEntry* spAnimationState_addAnimation (spAnimationState* self, int trackIndex, spAnimation* animation, int/*bool*/loop,
float delay) {
spTrackEntry* last;
spTrackEntry* entry = _spTrackEntry_create();
entry->animation = animation;
entry->loop = loop;
entry->endTime = animation->duration;
last = _spAnimationState_expandToIndex(self, trackIndex);
if (last) {
while (last->next)
last = last->next;
last->next = entry;
} else
self->tracks[trackIndex] = entry;
if (delay <= 0) {
if (previousAnimation)
delay = previousAnimation->duration - AnimationStateData_getMix(self->data, previousAnimation, animation) + delay;
if (last)
delay += last->endTime - spAnimationStateData_getMix(self->data, last->animation, animation);
else
delay = 0;
}
entry->delay = delay;
return entry;
}
void AnimationState_addAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop, float delay) {
Animation* animation = animationName ? SkeletonData_findAnimation(self->data->skeletonData, animationName) : 0;
AnimationState_addAnimation(self, animation, loop, delay);
spTrackEntry* spAnimationState_getCurrent (spAnimationState* self, int trackIndex) {
if (trackIndex >= self->trackCount) return 0;
return self->tracks[trackIndex];
}
void _AnimationState_setAnimation (AnimationState* self, Animation* newAnimation, int/*bool*/loop) {
_Internal* internal = SUB_CAST(_Internal, self);
internal->previous = 0;
if (newAnimation && self->animation && self->data) {
internal->mixDuration = AnimationStateData_getMix(self->data, self->animation, newAnimation);
if (internal->mixDuration > 0) {
internal->mixTime = 0;
internal->previous = self->animation;
internal->previousTime = self->time;
internal->previousLoop = self->loop;
}
}
CONST_CAST(Animation*, self->animation) = newAnimation;
self->loop = loop;
self->time = 0;
}
void AnimationState_setAnimation (AnimationState* self, Animation* newAnimation, int/*bool*/loop) {
_AnimationState_clearQueue(self);
_AnimationState_setAnimation(self, newAnimation, loop);
}
void AnimationState_setAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop) {
Animation* animation = animationName ? SkeletonData_findAnimation(self->data->skeletonData, animationName) : 0;
AnimationState_setAnimation(self, animation, loop);
}
void AnimationState_clearAnimation (AnimationState* self) {
_Internal* internal = SUB_CAST(_Internal, self);
internal->previous = 0;
CONST_CAST(Animation*, self->animation) = 0;
_AnimationState_clearQueue(self);
}
void AnimationState_update (AnimationState* self, float delta) {
_Entry* next;
_Internal* internal = SUB_CAST(_Internal, self);
self->time += delta;
internal->previousTime += delta;
internal->mixTime += delta;
if (internal->queue && self->time >= internal->queue->delay) {
_AnimationState_setAnimation(self, internal->queue->animation, internal->queue->loop);
next = internal->queue->next;
FREE(internal->queue);
internal->queue = next;
}
}
void AnimationState_apply (AnimationState* self, Skeleton* skeleton) {
_Internal* internal;
float alpha;
if (!self->animation) return;
internal = SUB_CAST(_Internal, self);
if (internal->previous) {
Animation_apply(internal->previous, skeleton, internal->previousTime, internal->previousLoop);
alpha = internal->mixTime / internal->mixDuration;
if (alpha >= 1) {
alpha = 1;
internal->previous = 0;
}
Animation_mix(self->animation, skeleton, self->time, self->loop, alpha);
} else
Animation_apply(self->animation, skeleton, self->time, self->loop);
}
int/*bool*/AnimationState_isComplete (AnimationState* self) {
return !self->animation || self->time >= self->animation->duration;
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,46 +29,93 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ANIMATIONSTATE_H_
#define SPINE_ANIMATIONSTATE_H_
#include <spine/Animation.h>
#include <spine/AnimationStateData.h>
#include <spine/Event.h>
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
AnimationStateData* const data;
Animation* const animation;
float time;
typedef enum {
ANIMATION_START, ANIMATION_END, ANIMATION_COMPLETE, ANIMATION_EVENT
} spEventType;
typedef struct spAnimationState spAnimationState;
typedef void (*spAnimationStateListener) (spAnimationState* state, int trackIndex, spEventType type, spEvent* event,
int loopCount);
typedef struct spTrackEntry spTrackEntry;
struct spTrackEntry {
spTrackEntry* next;
spTrackEntry* previous;
spAnimation* animation;
int/*bool*/loop;
} AnimationState;
float delay, time, lastTime, endTime, timeScale;
spAnimationStateListener listener;
float mixTime, mixDuration;
};
struct spAnimationState {
spAnimationStateData* const data;
float timeScale;
spAnimationStateListener listener;
void* context;
int trackCount;
spTrackEntry** tracks;
};
/* @param data May be 0 for no mixing. */
AnimationState* AnimationState_create (AnimationStateData* data);
void AnimationState_dispose (AnimationState* self);
spAnimationState* spAnimationState_create (spAnimationStateData* data);
void spAnimationState_dispose (spAnimationState* self);
void AnimationState_update (AnimationState* self, float delta);
void spAnimationState_update (spAnimationState* self, float delta);
void spAnimationState_apply (spAnimationState* self, struct spSkeleton* skeleton);
void AnimationState_apply (AnimationState* self, struct Skeleton* skeleton);
void spAnimationState_clearTracks (spAnimationState* self);
void spAnimationState_clearTrack (spAnimationState* self, int trackIndex);
/* @param animationName May be 0. */
void AnimationState_setAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop);
/* @param animation May be 0. */
void AnimationState_setAnimation (AnimationState* self, Animation* animation, int/*bool*/loop);
/** Set the current animation. Any queued animations are cleared. */
spTrackEntry* spAnimationState_setAnimationByName (spAnimationState* self, int trackIndex, const char* animationName,
int/*bool*/loop);
spTrackEntry* spAnimationState_setAnimation (spAnimationState* self, int trackIndex, spAnimation* animation, int/*bool*/loop);
/** @param animationName May be 0.
* @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */
void AnimationState_addAnimationByName (AnimationState* self, const char* animationName, int/*bool*/loop, float delay);
/** @param animation May be 0.
* @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */
void AnimationState_addAnimation (AnimationState* self, Animation* animation, int/*bool*/loop, float delay);
/** Adds an animation to be played delay seconds after the current or last queued animation, taking into account any mix
* duration. */
spTrackEntry* spAnimationState_addAnimationByName (spAnimationState* self, int trackIndex, const char* animationName,
int/*bool*/loop, float delay);
spTrackEntry* spAnimationState_addAnimation (spAnimationState* self, int trackIndex, spAnimation* animation, int/*bool*/loop,
float delay);
void AnimationState_clearAnimation (AnimationState* self);
spTrackEntry* spAnimationState_getCurrent (spAnimationState* self, int trackIndex);
int/*bool*/AnimationState_isComplete (AnimationState* self);
#ifdef SPINE_SHORT_NAMES
typedef spEventType EventType;
typedef spAnimationStateListener AnimationStateListener;
typedef spTrackEntry TrackEntry;
typedef spAnimationState AnimationState;
#define AnimationState_create(...) spAnimationState_create(__VA_ARGS__)
#define AnimationState_dispose(...) spAnimationState_dispose(__VA_ARGS__)
#define AnimationState_update(...) spAnimationState_update(__VA_ARGS__)
#define AnimationState_apply(...) spAnimationState_apply(__VA_ARGS__)
#define AnimationState_clearTracks(...) spAnimationState_clearTracks(__VA_ARGS__)
#define AnimationState_clearTrack(...) spAnimationState_clearTrack(__VA_ARGS__)
#define AnimationState_setAnimationByName(...) spAnimationState_setAnimationByName(__VA_ARGS__)
#define AnimationState_setAnimation(...) spAnimationState_setAnimation(__VA_ARGS__)
#define AnimationState_addAnimationByName(...) spAnimationState_addAnimationByName(__VA_ARGS__)
#define AnimationState_addAnimation(...) spAnimationState_addAnimation(__VA_ARGS__)
#define AnimationState_getCurrent(...) spAnimationState_getCurrent(__VA_ARGS__)
#endif
} // namespace spine {
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ANIMATIONSTATE_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,21 +29,19 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/AnimationStateData.h>
#include <spine/extension.h>
namespace spine {
typedef struct _ToEntry _ToEntry;
struct _ToEntry {
Animation* animation;
spAnimation* animation;
float duration;
_ToEntry* next;
};
_ToEntry* _ToEntry_create (Animation* to, float duration) {
_ToEntry* _ToEntry_create (spAnimation* to, float duration) {
_ToEntry* self = NEW(_ToEntry);
self->animation = to;
self->duration = duration;
@ -50,12 +56,12 @@ void _ToEntry_dispose (_ToEntry* self) {
typedef struct _FromEntry _FromEntry;
struct _FromEntry {
Animation* animation;
spAnimation* animation;
_ToEntry* toEntries;
_FromEntry* next;
};
_FromEntry* _FromEntry_create (Animation* from) {
_FromEntry* _FromEntry_create (spAnimation* from) {
_FromEntry* self = NEW(_FromEntry);
self->animation = from;
return self;
@ -67,13 +73,13 @@ void _FromEntry_dispose (_FromEntry* self) {
/**/
AnimationStateData* AnimationStateData_create (SkeletonData* skeletonData) {
AnimationStateData* self = NEW(AnimationStateData);
CONST_CAST(SkeletonData*, self->skeletonData) = skeletonData;
spAnimationStateData* spAnimationStateData_create (spSkeletonData* skeletonData) {
spAnimationStateData* self = NEW(spAnimationStateData);
CONST_CAST(spSkeletonData*, self->skeletonData) = skeletonData;
return self;
}
void AnimationStateData_dispose (AnimationStateData* self) {
void spAnimationStateData_dispose (spAnimationStateData* self) {
_ToEntry* toEntry;
_ToEntry* nextToEntry;
_FromEntry* nextFromEntry;
@ -94,16 +100,16 @@ void AnimationStateData_dispose (AnimationStateData* self) {
FREE(self);
}
void AnimationStateData_setMixByName (AnimationStateData* self, const char* fromName, const char* toName, float duration) {
Animation* to;
Animation* from = SkeletonData_findAnimation(self->skeletonData, fromName);
void spAnimationStateData_setMixByName (spAnimationStateData* self, const char* fromName, const char* toName, float duration) {
spAnimation* to;
spAnimation* from = spSkeletonData_findAnimation(self->skeletonData, fromName);
if (!from) return;
to = SkeletonData_findAnimation(self->skeletonData, toName);
to = spSkeletonData_findAnimation(self->skeletonData, toName);
if (!to) return;
AnimationStateData_setMix(self, from, to, duration);
spAnimationStateData_setMix(self, from, to, duration);
}
void AnimationStateData_setMix (AnimationStateData* self, Animation* from, Animation* to, float duration) {
void spAnimationStateData_setMix (spAnimationStateData* self, spAnimation* from, spAnimation* to, float duration) {
/* Find existing FromEntry. */
_ToEntry* toEntry;
_FromEntry* fromEntry = (_FromEntry*)self->entries;
@ -132,7 +138,7 @@ void AnimationStateData_setMix (AnimationStateData* self, Animation* from, Anima
fromEntry->toEntries = toEntry;
}
float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Animation* to) {
float spAnimationStateData_getMix (spAnimationStateData* self, spAnimation* from, spAnimation* to) {
_FromEntry* fromEntry = (_FromEntry*)self->entries;
while (fromEntry) {
if (fromEntry->animation == from) {
@ -144,7 +150,5 @@ float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Anim
}
fromEntry = fromEntry->next;
}
return 0;
return self->defaultMix;
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,7 +29,7 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ANIMATIONSTATEDATA_H_
#define SPINE_ANIMATIONSTATEDATA_H_
@ -29,21 +37,35 @@
#include <spine/Animation.h>
#include <spine/SkeletonData.h>
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
SkeletonData* const skeletonData;
spSkeletonData* const skeletonData;
float defaultMix;
const void* const entries;
} AnimationStateData;
} spAnimationStateData;
AnimationStateData* AnimationStateData_create (SkeletonData* skeletonData);
void AnimationStateData_dispose (AnimationStateData* self);
spAnimationStateData* spAnimationStateData_create (spSkeletonData* skeletonData);
void spAnimationStateData_dispose (spAnimationStateData* self);
void AnimationStateData_setMixByName (AnimationStateData* self, const char* fromName, const char* toName, float duration);
void AnimationStateData_setMix (AnimationStateData* self, Animation* from, Animation* to, float duration);
void spAnimationStateData_setMixByName (spAnimationStateData* self, const char* fromName, const char* toName, float duration);
void spAnimationStateData_setMix (spAnimationStateData* self, spAnimation* from, spAnimation* to, float duration);
/* Returns 0 if there is no mixing between the animations. */
float AnimationStateData_getMix (AnimationStateData* self, Animation* from, Animation* to);
float spAnimationStateData_getMix (spAnimationStateData* self, spAnimation* from, spAnimation* to);
} // namespace spine {
#ifdef SPINE_SHORT_NAMES
typedef spAnimationStateData AnimationStateData;
#define AnimationStateData_create(...) spAnimationStateData_create(__VA_ARGS__)
#define AnimationStateData_dispose(...) spAnimationStateData_dispose(__VA_ARGS__)
#define AnimationStateData_setMixByName(...) spAnimationStateData_setMixByName(__VA_ARGS__)
#define AnimationStateData_setMix(...) spAnimationStateData_setMix(__VA_ARGS__)
#define AnimationStateData_getMix(...) spAnimationStateData_getMix(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ANIMATIONSTATEDATA_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,33 +29,31 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/Atlas.h>
#include <ctype.h>
#include <spine/extension.h>
namespace spine {
AtlasPage* AtlasPage_create (const char* name) {
AtlasPage* self = NEW(AtlasPage);
spAtlasPage* spAtlasPage_create (const char* name) {
spAtlasPage* self = NEW(spAtlasPage);
MALLOC_STR(self->name, name);
return self;
}
void AtlasPage_dispose (AtlasPage* self) {
_AtlasPage_disposeTexture(self);
void spAtlasPage_dispose (spAtlasPage* self) {
_spAtlasPage_disposeTexture(self);
FREE(self->name);
FREE(self);
}
/**/
AtlasRegion* AtlasRegion_create () {
return NEW(AtlasRegion) ;
spAtlasRegion* spAtlasRegion_create () {
return NEW(spAtlasRegion) ;
}
void AtlasRegion_dispose (AtlasRegion* self) {
void spAtlasRegion_dispose (spAtlasRegion* self) {
FREE(self->name);
FREE(self->splits);
FREE(self->pads);
@ -116,7 +122,7 @@ static int readValue (const char* end, Str* str) {
/* Returns the number of tuple values read (2, 4, or 0 for failure). */
static int readTuple (const char* end, Str tuple[]) {
int i;
Str str = {NULL};
Str str;
readLine(0, end, &str);
if (!beginPast(&str, ':')) return 0;
@ -136,7 +142,7 @@ static int readTuple (const char* end, Str tuple[]) {
}
static char* mallocString (Str* str) {
size_t length = str->end - str->begin;
int length = str->end - str->begin;
char* string = MALLOC(char, length + 1);
memcpy(string, str->begin, length);
string[length] = '\0';
@ -144,7 +150,7 @@ static char* mallocString (Str* str) {
}
static int indexOf (const char** array, int count, Str* str) {
size_t length = str->end - str->begin;
int length = str->end - str->begin;
int i;
for (i = count - 1; i >= 0; i--)
if (strncmp(array[i], str->begin, length) == 0) return i;
@ -156,11 +162,11 @@ static int equals (Str* str, const char* other) {
}
static int toInt (Str* str) {
return static_cast<int>(strtol(str->begin, (char**)&str->end, 10));
return strtol(str->begin, (char**)&str->end, 10);
}
static Atlas* abortAtlas (Atlas* self) {
Atlas_dispose(self);
static spAtlas* abortAtlas (spAtlas* self) {
spAtlas_dispose(self);
return 0;
}
@ -168,17 +174,17 @@ static const char* formatNames[] = {"Alpha", "Intensity", "LuminanceAlpha", "RGB
static const char* textureFilterNames[] = {"Nearest", "Linear", "MipMap", "MipMapNearestNearest", "MipMapLinearNearest",
"MipMapNearestLinear", "MipMapLinearLinear"};
Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) {
spAtlas* spAtlas_readAtlas (const char* begin, int length, const char* dir) {
int count;
const char* end = begin + length;
size_t dirLength = strlen(dir);
int dirLength = strlen(dir);
int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\';
Atlas* self = NEW(Atlas);
spAtlas* self = NEW(spAtlas);
AtlasPage *page = 0;
AtlasPage *lastPage = 0;
AtlasRegion *lastRegion = 0;
spAtlasPage *page = 0;
spAtlasPage *lastPage = 0;
spAtlasRegion *lastRegion = 0;
Str str;
Str tuple[4];
readLine(begin, 0, 0);
@ -192,7 +198,7 @@ Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) {
if (needsSlash) path[dirLength] = '/';
strcpy(path + dirLength + needsSlash, name);
page = AtlasPage_create(name);
page = spAtlasPage_create(name);
FREE(name);
if (lastPage)
lastPage->next = page;
@ -201,11 +207,11 @@ Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) {
lastPage = page;
if (!readValue(end, &str)) return abortAtlas(self);
page->format = (AtlasFormat)indexOf(formatNames, 7, &str);
page->format = (spAtlasFormat)indexOf(formatNames, 7, &str);
if (!readTuple(end, tuple)) return abortAtlas(self);
page->minFilter = (AtlasFilter)indexOf(textureFilterNames, 7, tuple);
page->magFilter = (AtlasFilter)indexOf(textureFilterNames, 7, tuple + 1);
page->minFilter = (spAtlasFilter)indexOf(textureFilterNames, 7, tuple);
page->magFilter = (spAtlasFilter)indexOf(textureFilterNames, 7, tuple + 1);
if (!readValue(end, &str)) return abortAtlas(self);
if (!equals(&str, "none")) {
@ -213,10 +219,10 @@ Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) {
page->vWrap = *str.begin == 'x' ? ATLAS_CLAMPTOEDGE : (*str.begin == 'y' ? ATLAS_REPEAT : ATLAS_REPEAT);
}
_AtlasPage_createTexture(page, path);
_spAtlasPage_createTexture(page, path);
FREE(path);
} else {
AtlasRegion *region = AtlasRegion_create();
spAtlasRegion *region = spAtlasRegion_create();
if (lastRegion)
lastRegion->next = region;
else
@ -282,58 +288,56 @@ Atlas* Atlas_readAtlas (const char* begin, int length, const char* dir) {
return self;
}
Atlas* Atlas_readAtlasFile (const char* path) {
spAtlas* spAtlas_readAtlasFile (const char* path) {
int dirLength;
char *dir;
ssize_t length;
int length;
const char* data;
Atlas* atlas = 0;
spAtlas* atlas = 0;
/* Get directory from atlas path. */
const char* lastForwardSlash = strrchr(path, '/');
const char* lastBackwardSlash = strrchr(path, '\\');
const char* lastSlash = lastForwardSlash > lastBackwardSlash ? lastForwardSlash : lastBackwardSlash;
if (lastSlash == path) lastSlash++; /* Never drop starting slash. */
dirLength = static_cast<int>(lastSlash ? lastSlash - path : 0);
dirLength = lastSlash ? lastSlash - path : 0;
dir = MALLOC(char, dirLength + 1);
memcpy(dir, path, dirLength);
dir[dirLength] = '\0';
data = _Util_readFile(path, &length);
if (data) atlas = Atlas_readAtlas(data, static_cast<int>(length), dir);
data = _spUtil_readFile(path, &length);
if (data) atlas = spAtlas_readAtlas(data, length, dir);
FREE(data);
FREE(dir);
return atlas;
}
void Atlas_dispose (Atlas* self) {
AtlasRegion* region, *nextRegion;
AtlasPage* page = self->pages;
void spAtlas_dispose (spAtlas* self) {
spAtlasRegion* region, *nextRegion;
spAtlasPage* page = self->pages;
while (page) {
AtlasPage* nextPage = page->next;
AtlasPage_dispose(page);
spAtlasPage* nextPage = page->next;
spAtlasPage_dispose(page);
page = nextPage;
}
region = self->regions;
while (region) {
nextRegion = region->next;
AtlasRegion_dispose(region);
spAtlasRegion_dispose(region);
region = nextRegion;
}
FREE(self);
}
AtlasRegion* Atlas_findRegion (const Atlas* self, const char* name) {
AtlasRegion* region = self->regions;
spAtlasRegion* spAtlas_findRegion (const spAtlas* self, const char* name) {
spAtlasRegion* region = self->regions;
while (region) {
if (strcmp(region->name, name) == 0) return region;
region = region->next;
}
return 0;
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,16 +29,18 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ATLAS_H_
#define SPINE_ATLAS_H_
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
ATLAS_ALPHA, ATLAS_INTENSITY, ATLAS_LUMINANCE_ALPHA, ATLAS_RGB565, ATLAS_RGBA4444, ATLAS_RGB888, ATLAS_RGBA8888
} AtlasFormat;
} spAtlasFormat;
typedef enum {
ATLAS_NEAREST,
@ -40,32 +50,41 @@ typedef enum {
ATLAS_MIPMAP_LINEAR_NEAREST,
ATLAS_MIPMAP_NEAREST_LINEAR,
ATLAS_MIPMAP_LINEAR_LINEAR
} AtlasFilter;
} spAtlasFilter;
typedef enum {
ATLAS_MIRROREDREPEAT, ATLAS_CLAMPTOEDGE, ATLAS_REPEAT
} AtlasWrap;
} spAtlasWrap;
typedef struct AtlasPage AtlasPage;
struct AtlasPage {
typedef struct spAtlasPage spAtlasPage;
struct spAtlasPage {
const char* name;
AtlasFormat format;
AtlasFilter minFilter, magFilter;
AtlasWrap uWrap, vWrap;
spAtlasFormat format;
spAtlasFilter minFilter, magFilter;
spAtlasWrap uWrap, vWrap;
void* rendererObject;
int width, height;
AtlasPage* next;
spAtlasPage* next;
};
AtlasPage* AtlasPage_create (const char* name);
void AtlasPage_dispose (AtlasPage* self);
spAtlasPage* spAtlasPage_create (const char* name);
void spAtlasPage_dispose (spAtlasPage* self);
#ifdef SPINE_SHORT_NAMES
typedef spAtlasFormat AtlasFormat;
typedef spAtlasFilter AtlasFilter;
typedef spAtlasWrap AtlasWrap;
typedef spAtlasPage AtlasPage;
#define AtlasPage_create(...) spAtlasPage_create(__VA_ARGS__)
#define AtlasPage_dispose(...) spAtlasPage_dispose(__VA_ARGS__)
#endif
/**/
typedef struct AtlasRegion AtlasRegion;
struct AtlasRegion {
typedef struct spAtlasRegion spAtlasRegion;
struct spAtlasRegion {
const char* name;
int x, y, width, height;
float u, v, u2, v2;
@ -77,30 +96,46 @@ struct AtlasRegion {
int* splits;
int* pads;
AtlasPage* page;
spAtlasPage* page;
AtlasRegion* next;
spAtlasRegion* next;
};
AtlasRegion* AtlasRegion_create ();
void AtlasRegion_dispose (AtlasRegion* self);
spAtlasRegion* spAtlasRegion_create ();
void spAtlasRegion_dispose (spAtlasRegion* self);
#ifdef SPINE_SHORT_NAMES
typedef spAtlasRegion AtlasRegion;
#define AtlasRegion_create(...) spAtlasRegion_create(__VA_ARGS__)
#define AtlasRegion_dispose(...) spAtlasRegion_dispose(__VA_ARGS__)
#endif
/**/
typedef struct {
AtlasPage* pages;
AtlasRegion* regions;
} Atlas;
spAtlasPage* pages;
spAtlasRegion* regions;
} spAtlas;
/* Image files referenced in the atlas file will be prefixed with dir. */
Atlas* Atlas_readAtlas (const char* data, int length, const char* dir);
spAtlas* spAtlas_readAtlas (const char* data, int length, const char* dir);
/* Image files referenced in the atlas file will be prefixed with the directory containing the atlas file. */
Atlas* Atlas_readAtlasFile (const char* path);
void Atlas_dispose (Atlas* atlas);
spAtlas* spAtlas_readAtlasFile (const char* path);
void spAtlas_dispose (spAtlas* atlas);
/* Returns 0 if the region was not found. */
AtlasRegion* Atlas_findRegion (const Atlas* self, const char* name);
spAtlasRegion* spAtlas_findRegion (const spAtlas* self, const char* name);
} // namespace spine {
#ifdef SPINE_SHORT_NAMES
typedef spAtlas Atlas;
#define Atlas_readAtlas(...) spAtlas_readAtlas(__VA_ARGS__)
#define Atlas_readAtlasFile(...) spAtlas_readAtlasFile(__VA_ARGS__)
#define Atlas_dispose(...) spAtlas_dispose(__VA_ARGS__)
#define Atlas_findRegion(...) spAtlas_findRegion(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ATLAS_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,26 +29,25 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/AtlasAttachmentLoader.h>
#include <spine/extension.h>
namespace spine {
Attachment* _AtlasAttachmentLoader_newAttachment (AttachmentLoader* loader, Skin* skin, AttachmentType type, const char* name) {
AtlasAttachmentLoader* self = SUB_CAST(AtlasAttachmentLoader, loader);
spAttachment* _spAtlasAttachmentLoader_newAttachment (spAttachmentLoader* loader, spSkin* skin, spAttachmentType type,
const char* name) {
spAtlasAttachmentLoader* self = SUB_CAST(spAtlasAttachmentLoader, loader);
switch (type) {
case ATTACHMENT_REGION: {
RegionAttachment* attachment;
AtlasRegion* region = Atlas_findRegion(self->atlas, name);
spRegionAttachment* attachment;
spAtlasRegion* region = spAtlas_findRegion(self->atlas, name);
if (!region) {
_AttachmentLoader_setError(loader, "Region not found: ", name);
_spAttachmentLoader_setError(loader, "Region not found: ", name);
return 0;
}
attachment = RegionAttachment_create(name);
attachment = spRegionAttachment_create(name);
attachment->rendererObject = region;
RegionAttachment_setUVs(attachment, region->u, region->v, region->u2, region->v2, region->rotate);
spRegionAttachment_setUVs(attachment, region->u, region->v, region->u2, region->v2, region->rotate);
attachment->regionOffsetX = region->offsetX;
attachment->regionOffsetY = region->offsetY;
attachment->regionWidth = region->width;
@ -49,17 +56,17 @@ Attachment* _AtlasAttachmentLoader_newAttachment (AttachmentLoader* loader, Skin
attachment->regionOriginalHeight = region->originalHeight;
return SUPER(attachment);
}
case ATTACHMENT_BOUNDING_BOX:
return SUPER(spBoundingBoxAttachment_create(name));
default:
_AttachmentLoader_setUnknownTypeError(loader, type);
_spAttachmentLoader_setUnknownTypeError(loader, type);
return 0;
}
}
AtlasAttachmentLoader* AtlasAttachmentLoader_create (Atlas* atlas) {
AtlasAttachmentLoader* self = NEW(AtlasAttachmentLoader);
_AttachmentLoader_init(SUPER(self), _AttachmentLoader_deinit, _AtlasAttachmentLoader_newAttachment);
spAtlasAttachmentLoader* spAtlasAttachmentLoader_create (spAtlas* atlas) {
spAtlasAttachmentLoader* self = NEW(spAtlasAttachmentLoader);
_spAttachmentLoader_init(SUPER(self), _spAttachmentLoader_deinit, _spAtlasAttachmentLoader_newAttachment);
self->atlas = atlas;
return self;
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,7 +29,7 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ATLASATTACHMENTLOADER_H_
#define SPINE_ATLASATTACHMENTLOADER_H_
@ -29,15 +37,24 @@
#include <spine/AttachmentLoader.h>
#include <spine/Atlas.h>
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
AttachmentLoader super;
Atlas* atlas;
} AtlasAttachmentLoader;
spAttachmentLoader super;
spAtlas* atlas;
} spAtlasAttachmentLoader;
AtlasAttachmentLoader* AtlasAttachmentLoader_create (Atlas* atlas);
spAtlasAttachmentLoader* spAtlasAttachmentLoader_create (spAtlas* atlas);
} // namespace spine {
#ifdef SPINE_SHORT_NAMES
typedef spAtlasAttachmentLoader AtlasAttachmentLoader;
#define AtlasAttachmentLoader_create(...) spAtlasAttachmentLoader_create(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ATLASATTACHMENTLOADER_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,36 +29,31 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/Attachment.h>
#include <spine/extension.h>
#include <spine/Slot.h>
namespace spine {
typedef struct _spAttachmentVtable {
void (*dispose) (spAttachment* self);
} _spAttachmentVtable;
typedef struct _AttachmentVtable {
void (*dispose) (Attachment* self);
} _AttachmentVtable;
void _spAttachment_init (spAttachment* self, const char* name, spAttachmentType type, /**/
void (*dispose) (spAttachment* self)) {
void _Attachment_init (Attachment* self, const char* name, AttachmentType type, /**/
void (*dispose) (Attachment* self)) {
CONST_CAST(_AttachmentVtable*, self->vtable) = NEW(_AttachmentVtable);
VTABLE(Attachment, self) ->dispose = dispose;
CONST_CAST(_spAttachmentVtable*, self->vtable) = NEW(_spAttachmentVtable);
VTABLE(spAttachment, self) ->dispose = dispose;
MALLOC_STR(self->name, name);
self->type = type;
}
void _Attachment_deinit (Attachment* self) {
void _spAttachment_deinit (spAttachment* self) {
FREE(self->vtable);
FREE(self->name);
}
void Attachment_dispose (Attachment* self) {
VTABLE(Attachment, self) ->dispose(self);
FREE(self);
void spAttachment_dispose (spAttachment* self) {
VTABLE(spAttachment, self) ->dispose(self);
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,29 +29,39 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ATTACHMENT_H_
#define SPINE_ATTACHMENT_H_
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
struct Slot;
struct spSlot;
typedef enum {
ATTACHMENT_REGION, ATTACHMENT_REGION_SEQUENCE
} AttachmentType;
ATTACHMENT_REGION, ATTACHMENT_REGION_SEQUENCE, ATTACHMENT_BOUNDING_BOX
} spAttachmentType;
typedef struct Attachment Attachment;
struct Attachment {
typedef struct spAttachment spAttachment;
struct spAttachment {
const char* const name;
AttachmentType type;
spAttachmentType type;
const void* const vtable;
};
void Attachment_dispose (Attachment* self);
void spAttachment_dispose (spAttachment* self);
} // namespace spine {
#ifdef SPINE_SHORT_NAMES
typedef spAttachmentType AttachmentType;
typedef spAttachment Attachment;
#define Attachment_dispose(...) spAttachment_dispose(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ATTACHMENT_H_ */

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,57 +29,53 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#include <spine/AttachmentLoader.h>
#include <stdio.h>
#include <spine/extension.h>
namespace spine {
typedef struct _spAttachmentLoaderVtable {
spAttachment* (*newAttachment) (spAttachmentLoader* self, spSkin* skin, spAttachmentType type, const char* name);
void (*dispose) (spAttachmentLoader* self);
} _spAttachmentLoaderVtable;
typedef struct _AttachmentLoaderVtable {
Attachment* (*newAttachment) (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name);
void (*dispose) (AttachmentLoader* self);
} _AttachmentLoaderVtable;
void _AttachmentLoader_init (AttachmentLoader* self, /**/
void (*dispose) (AttachmentLoader* self), /**/
Attachment* (*newAttachment) (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name)) {
CONST_CAST(_AttachmentLoaderVtable*, self->vtable) = NEW(_AttachmentLoaderVtable);
VTABLE(AttachmentLoader, self) ->dispose = dispose;
VTABLE(AttachmentLoader, self) ->newAttachment = newAttachment;
void _spAttachmentLoader_init (spAttachmentLoader* self, /**/
void (*dispose) (spAttachmentLoader* self), /**/
spAttachment* (*newAttachment) (spAttachmentLoader* self, spSkin* skin, spAttachmentType type, const char* name)) {
CONST_CAST(_spAttachmentLoaderVtable*, self->vtable) = NEW(_spAttachmentLoaderVtable);
VTABLE(spAttachmentLoader, self)->dispose = dispose;
VTABLE(spAttachmentLoader, self)->newAttachment = newAttachment;
}
void _AttachmentLoader_deinit (AttachmentLoader* self) {
void _spAttachmentLoader_deinit (spAttachmentLoader* self) {
FREE(self->vtable);
FREE(self->error1);
FREE(self->error2);
}
void AttachmentLoader_dispose (AttachmentLoader* self) {
VTABLE(AttachmentLoader, self) ->dispose(self);
void spAttachmentLoader_dispose (spAttachmentLoader* self) {
VTABLE(spAttachmentLoader, self)->dispose(self);
FREE(self);
}
Attachment* AttachmentLoader_newAttachment (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name) {
spAttachment* spAttachmentLoader_newAttachment (spAttachmentLoader* self, spSkin* skin, spAttachmentType type, const char* name) {
FREE(self->error1);
FREE(self->error2);
self->error1 = 0;
self->error2 = 0;
return VTABLE(AttachmentLoader, self) ->newAttachment(self, skin, type, name);
return VTABLE(spAttachmentLoader, self)->newAttachment(self, skin, type, name);
}
void _AttachmentLoader_setError (AttachmentLoader* self, const char* error1, const char* error2) {
void _spAttachmentLoader_setError (spAttachmentLoader* self, const char* error1, const char* error2) {
FREE(self->error1);
FREE(self->error2);
MALLOC_STR(self->error1, error1);
MALLOC_STR(self->error2, error2);
}
void _AttachmentLoader_setUnknownTypeError (AttachmentLoader* self, AttachmentType type) {
void _spAttachmentLoader_setUnknownTypeError (spAttachmentLoader* self, spAttachmentType type) {
char buffer[16];
sprintf(buffer, "%d", type);
_AttachmentLoader_setError(self, "Unknown attachment type: ", buffer);
_spAttachmentLoader_setError(self, "Unknown attachment type: ", buffer);
}
} // namespace spine {

View File

@ -1,15 +1,23 @@
/*******************************************************************************
/******************************************************************************
* Spine Runtime Software License - Version 1.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistribution and use in source and binary forms in whole or in part, with
* or without modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 1. A Spine Essential, Professional, Enterprise, or Education License must
* be purchased from Esoteric Software and the license must remain valid:
* http://esotericsoftware.com/
* 2. Redistributions of source code must retain this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer.
* 3. Redistributions in binary form must reproduce this license, which is the
* above copyright notice, this declaration of conditions and the following
* disclaimer, in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
@ -21,7 +29,7 @@
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
*****************************************************************************/
#ifndef SPINE_ATTACHMENTLOADER_H_
#define SPINE_ATTACHMENTLOADER_H_
@ -29,24 +37,38 @@
#include <spine/Attachment.h>
#include <spine/Skin.h>
namespace spine {
#ifdef __cplusplus
extern "C" {
#endif
typedef struct AttachmentLoader AttachmentLoader;
struct AttachmentLoader {
typedef struct spAttachmentLoader spAttachmentLoader;
struct spAttachmentLoader {
const char* error1;
const char* error2;
const void* const vtable;
#ifdef __cplusplus
AttachmentLoader () : error1(0), error2(0), vtable(0) {}
spAttachmentLoader () :
error1(0),
error2(0),
vtable(0) {
}
#endif
};
void AttachmentLoader_dispose (AttachmentLoader* self);
void spAttachmentLoader_dispose (spAttachmentLoader* self);
/* Returns 0 to not load an attachment. If 0 is returned and AttachmentLoader.error1 is set, an error occurred. */
Attachment* AttachmentLoader_newAttachment (AttachmentLoader* self, Skin* skin, AttachmentType type, const char* name);
/* Returns 0 to not load an attachment. If 0 is returned and spAttachmentLoader.error1 is set, an error occurred. */
spAttachment* spAttachmentLoader_newAttachment (spAttachmentLoader* self, spSkin* skin, spAttachmentType type, const char* name);
} // namespace spine {
#ifdef SPINE_SHORT_NAMES
typedef spAttachmentLoader AttachmentLoader;
#define AttachmentLoader_dispose(...) spAttachmentLoader_dispose(__VA_ARGS__)
#define AttachmentLoader_newAttachment(...) spAttachmentLoader_newAttachment(__VA_ARGS__)
#endif
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ATTACHMENTLOADER_H_ */

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