From 8626455d697ae7da902aa5974155b1ce92152e0b Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 25 Jul 2013 20:52:16 +0800 Subject: [PATCH 1/9] Adding CCControl js binding. --- .../javascript/bindings/ScriptingCore.cpp | 102 ++++++++++-------- scripting/javascript/bindings/ScriptingCore.h | 2 +- .../bindings/js/jsb_cocos2d_extension.js | 18 ++++ .../javascript/bindings/js_bindings_config.h | 3 + .../jsb_cocos2dx_extension_manual.cpp | 96 +++++++++++++++++ 5 files changed, 174 insertions(+), 47 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 241bb2d33c..8246eb7ba2 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -168,11 +168,14 @@ static void removeJSTouchObject(JSContext *cx, Touch *x, jsval &jsret) { } } -void ScriptingCore::executeJSFunctionWithThisObj(jsval thisObj, jsval callback, - jsval *data) { - jsval retval; +void ScriptingCore::executeJSFunctionWithThisObj(jsval thisObj, + jsval callback, + uint32_t argc/* = 0*/, + jsval* vp/* = NULL*/, + jsval* retVal/* = NULL*/) +{ if(callback != JSVAL_VOID || thisObj != JSVAL_VOID) { - JS_CallFunctionValue(cx_, JSVAL_TO_OBJECT(thisObj), callback, 1, data, &retval); + JS_CallFunctionValue(cx_, JSVAL_TO_OBJECT(thisObj), callback, argc, vp, retVal); } } @@ -1099,9 +1102,9 @@ JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *outval ) JSBool ok = JS_TRUE; double dp; ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ok &= !isnan(dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); *outval = (int32_t)dp; @@ -1113,9 +1116,9 @@ JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *outval ) JSBool ok = JS_TRUE; double dp; ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ok &= !isnan(dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); *outval = (uint32_t)dp; @@ -1127,9 +1130,9 @@ JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) JSBool ok = JS_TRUE; double dp; ok &= JS_ValueToNumber(cx, vp, &dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ok &= !isnan(dp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); *outval = (uint16_t)dp; @@ -1139,9 +1142,9 @@ JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *outval ) JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { JSObject *tmp_arg; JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION2( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); + JSB_PRECONDITION3( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(long long), cx, JS_FALSE, "Invalid Typed Array length"); uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); long long ret = arg_array[0]; @@ -1153,8 +1156,8 @@ JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) { } JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) { - JSString *tmp = JS_ValueToString(cx, v); - JSB_PRECONDITION2(tmp, cx, JS_FALSE, "Error processing arguments"); + JSString *tmp = v.isString() ? JS_ValueToString(cx, v) : NULL; + JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments"); JSStringWrapper str(tmp); *ret = str.get(); @@ -1165,13 +1168,14 @@ JSBool jsval_to_ccpoint(JSContext *cx, jsval v, Point* ret) { JSObject *tmp; jsval jsx, jsy; double x, y; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "x", &jsx) && JS_GetProperty(cx, tmp, "y", &jsy) && JS_ValueToNumber(cx, jsx, &x) && JS_ValueToNumber(cx, jsy, &y); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->x = (float)x; ret->y = (float)y; @@ -1182,17 +1186,18 @@ JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { JSObject *tmp; jsval jsx, jsy, jsz, jstimestamp; double x, y, timestamp, z; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && - JS_GetProperty(cx, tmp, "x", &jsx) && - JS_GetProperty(cx, tmp, "y", &jsy) && - JS_GetProperty(cx, tmp, "z", &jsz) && - JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jsz, &z) && - JS_ValueToNumber(cx, jstimestamp, ×tamp); + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && + JS_GetProperty(cx, tmp, "x", &jsx) && + JS_GetProperty(cx, tmp, "y", &jsy) && + JS_GetProperty(cx, tmp, "z", &jsz) && + JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && + JS_ValueToNumber(cx, jsx, &x) && + JS_ValueToNumber(cx, jsy, &y) && + JS_ValueToNumber(cx, jsz, &z) && + JS_ValueToNumber(cx, jstimestamp, ×tamp); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->x = x; ret->y = y; @@ -1234,7 +1239,7 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r vp++; } *ret = pArray; - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); return ok; } @@ -1242,7 +1247,8 @@ JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { JSObject *tmp; jsval jsx, jsy, jswidth, jsheight; double x, y, width, height; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "x", &jsx) && JS_GetProperty(cx, tmp, "y", &jsy) && JS_GetProperty(cx, tmp, "width", &jswidth) && @@ -1252,7 +1258,7 @@ JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { JS_ValueToNumber(cx, jswidth, &width) && JS_ValueToNumber(cx, jsheight, &height); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->origin.x = x; ret->origin.y = y; @@ -1265,13 +1271,14 @@ JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { JSObject *tmp; jsval jsw, jsh; double w, h; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "width", &jsw) && JS_GetProperty(cx, tmp, "height", &jsh) && JS_ValueToNumber(cx, jsw, &w) && JS_ValueToNumber(cx, jsh, &h); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->width = w; ret->height = h; return JS_TRUE; @@ -1281,7 +1288,8 @@ JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { JSObject *tmp; jsval jsr, jsg, jsb, jsa; double r, g, b, a; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && @@ -1291,7 +1299,7 @@ JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { JS_ValueToNumber(cx, jsb, &b) && JS_ValueToNumber(cx, jsa, &a); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->r = r; ret->g = g; @@ -1304,7 +1312,8 @@ JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { JSObject *tmp; jsval jsr, jsg, jsb, jsa; double r, g, b, a; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && @@ -1314,7 +1323,7 @@ JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { JS_ValueToNumber(cx, jsb, &b) && JS_ValueToNumber(cx, jsa, &a); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->r = r; ret->g = g; ret->b = b; @@ -1326,7 +1335,8 @@ JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { JSObject *tmp; jsval jsr, jsg, jsb; double r, g, b; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + JSBool ok = v.isObject() && + JS_ValueToObject(cx, v, &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && @@ -1334,7 +1344,7 @@ JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { JS_ValueToNumber(cx, jsg, &g) && JS_ValueToNumber(cx, jsb, &b); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); ret->r = r; ret->g = g; @@ -1345,9 +1355,9 @@ JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { // Parsing sequence JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); uint32_t len; JS_GetArrayLength(cx, jsobj, &len); @@ -1359,7 +1369,7 @@ JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int * JS_GetElement(cx, jsobj, i, &valarg); ok = jsval_to_ccpoint(cx, valarg, &array[i]); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); } *numPoints = len; @@ -1371,9 +1381,9 @@ JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int * JSBool jsval_to_ccarray(JSContext* cx, jsval v, Array** ret) { JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); + JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, jsobj, &len); @@ -1658,7 +1668,7 @@ JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) JS_ValueToNumber(cx, jstx, &tx) && JS_ValueToNumber(cx, jsty, &ty); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); *ret = AffineTransformMake(a, b, c, d, tx, ty); return JS_TRUE; diff --git a/scripting/javascript/bindings/ScriptingCore.h b/scripting/javascript/bindings/ScriptingCore.h index 4a54bce2bb..d8f872709c 100644 --- a/scripting/javascript/bindings/ScriptingCore.h +++ b/scripting/javascript/bindings/ScriptingCore.h @@ -94,7 +94,7 @@ public: bool executeFunctionWithObjectData(Node *self, const char *name, JSObject *obj); JSBool executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc = 0, jsval* vp = NULL, jsval* retVal = NULL); - void executeJSFunctionWithThisObj(jsval thisObj, jsval callback, jsval *data); + void executeJSFunctionWithThisObj(jsval thisObj, jsval callback, uint32_t argc = 0, jsval* vp = NULL, jsval* retVal = NULL); /** * will eval the specified string diff --git a/scripting/javascript/bindings/js/jsb_cocos2d_extension.js b/scripting/javascript/bindings/js/jsb_cocos2d_extension.js index 3272bc7765..73cb3a3e6d 100644 --- a/scripting/javascript/bindings/js/jsb_cocos2d_extension.js +++ b/scripting/javascript/bindings/js/jsb_cocos2d_extension.js @@ -135,6 +135,24 @@ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3; */ cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4; +cc.CONTROL_EVENT_TOTAL_NUMBER = 9; + +cc.CONTROL_EVENT_TOUCH_DOWN = 1 << 0; // A touch-down event in the control. +cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE = 1 << 1; // An event where a finger is dragged inside the bounds of the control. +cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE = 1 << 2; // An event where a finger is dragged just outside the bounds of the control. +cc.CONTROL_EVENT_TOUCH_DRAG_ENTER = 1 << 3; // An event where a finger is dragged into the bounds of the control. +cc.CONTROL_EVENT_TOUCH_DRAG_EXIT = 1 << 4; // An event where a finger is dragged from within a control to outside its bounds. +cc.CONTROL_EVENT_TOUCH_UP_INSIDE = 1 << 5; // A touch-up event in the control where the finger is inside the bounds of the control. +cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE = 1 << 6; // A touch-up event in the control where the finger is outside the bounds of the control. +cc.CONTROL_EVENT_TOUCH_CANCEL = 1 << 7; // A system event canceling the current touches for the control. +cc.CONTROL_EVENT_VALUECHANGED = 1 << 8; // A touch dragging or otherwise manipulating a control; causing it to emit a series of different values. + +cc.CONTROL_STATE_NORMAL = 1 << 0; // The normal; or default state of a controlę¢©hat is; enabled but neither selected nor highlighted. +cc.CONTROL_STATE_HIGHLIGHTED = 1 << 1; // Highlighted state of a control. A control enters this state when a touch down; drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. +cc.CONTROL_STATE_DISABLED = 1 << 2; // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. +cc.CONTROL_STATE_SELECTED = 1 << 3; // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. +cc.CONTROL_STATE_INITIAL = 1 << 3; + // PhysicsDebugNode cc.PhysicsDebugNode.create = function( space ) { var s = space; diff --git a/scripting/javascript/bindings/js_bindings_config.h b/scripting/javascript/bindings/js_bindings_config.h index 3950f9a79f..2216f2fca2 100644 --- a/scripting/javascript/bindings/js_bindings_config.h +++ b/scripting/javascript/bindings/js_bindings_config.h @@ -71,6 +71,9 @@ } while(0) #endif +#define JSB_PRECONDITION3( condition, context, ret_value, ...) do { \ + if( ! (condition) ) return (ret_value); \ + } while(0) /** @def JSB_REPRESENT_LONGLONG_AS_STR diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index ed4e6eb79d..83d38800cc 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -572,10 +572,104 @@ static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, js return JS_FALSE; } +class JSB_ControlButtonTarget : public Object { +public: + virtual void onEvent(Object *controlButton, ControlEvent event) { + js_proxy_t * p; + JS_GET_PROXY(p, controlButton); + if (!p) { + log("Failed to get proxy for control button"); + return; + } + + jsval dataVal[2]; + dataVal[0] = OBJECT_TO_JSVAL(p->obj); + int arg1 = event; + dataVal[1] = INT_TO_JSVAL(arg1); + + ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc));//, 2, dataVal); + } + + void setJSTarget(JSObject* pJSTarget) + { + _jsTarget = pJSTarget; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_jsTarget, "JSB_ControlButtonTarget"); + } + + void setJSAction(JSObject* jsFunc) { + _jsFunc = jsFunc; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_jsFunc, "JSB_ControlButtonTarget"); + } +private: + JSObject* _jsTarget; + JSObject* _jsFunc; +}; + +static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy; JS_GET_NATIVE_PROXY(proxy, obj); + cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + JSBool ok = JS_TRUE; + if (argc == 3) { + JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]); + JS_GET_NATIVE_PROXY(proxy, tmpObj); + cocos2d::Object *arg0 = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg0); + + int arg2; + ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); + + // save the delegate + JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); + JSB_ControlButtonTarget* nativeDelegate = new JSB_ControlButtonTarget(); + nativeDelegate->setJSTarget(jsDelegate); + nativeDelegate->setJSAction(JSVAL_TO_OBJECT(argv[1])); + cobj->addTargetWithActionForControlEvents(nativeDelegate, cccontrol_selector(JSB_ControlButtonTarget::onEvent), arg2); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3); + return JS_FALSE; +} + +static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) +{ + jsval *argv = JS_ARGV(cx, vp); + JSObject *obj = JS_THIS_OBJECT(cx, vp); + js_proxy_t *proxy; JS_GET_NATIVE_PROXY(proxy, obj); + cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + + if (argc == 3) { + obj = JSVAL_TO_OBJECT(argv[0]); + JS_GET_NATIVE_PROXY(proxy, obj); + cocos2d::Object *arg0 = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg0); + + obj = JSVAL_TO_OBJECT(argv[2]); + JS_GET_NATIVE_PROXY(proxy, obj); + cocos2d::extension::ControlEvent *arg2 = (cocos2d::extension::ControlEvent *)(proxy ? proxy->ptr : NULL); + TEST_NATIVE_OBJECT(cx, arg2); + + return JS_TRUE; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3); + return JS_FALSE; +} extern JSObject* jsb_ScrollView_prototype; extern JSObject* jsb_TableView_prototype; extern JSObject* jsb_EditBox_prototype; +extern JSObject* jsb_Control_prototype; void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) { @@ -583,6 +677,8 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JSObject* global) JS_DefineFunction(cx, jsb_TableView_prototype, "setDelegate", js_cocos2dx_CCTableView_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsb_TableView_prototype, "setDataSource", js_cocos2dx_CCTableView_setDataSource, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsb_EditBox_prototype, "setDelegate", js_cocos2dx_CCEditBox_setDelegate, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "addTargetWithActionForControlEvents", js_cocos2dx_CCControl_addTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, jsb_Control_prototype, "removeTargetWithActionForControlEvents", js_cocos2dx_CCControl_removeTargetWithActionForControlEvents, 3, JSPROP_READONLY | JSPROP_PERMANENT); JSObject *tmpObj = JSVAL_TO_OBJECT(anonEvaluate(cx, global, "(function () { return cc.TableView; })()")); JS_DefineFunction(cx, tmpObj, "create", js_cocos2dx_CCTableView_create, 3, JSPROP_READONLY | JSPROP_PERMANENT); From 78ad7bcb4811dc37846a3517a50ea2d2c5a38e13 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 5 Aug 2013 10:03:02 +0800 Subject: [PATCH 2/9] ControlEvent --> Control::EventType. --- .../bindings/jsb_cocos2dx_extension_manual.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 83d38800cc..39109e34c8 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -574,7 +574,7 @@ static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, js class JSB_ControlButtonTarget : public Object { public: - virtual void onEvent(Object *controlButton, ControlEvent event) { + virtual void onEvent(Object *controlButton, Control::EventType event) { js_proxy_t * p; JS_GET_PROXY(p, controlButton); if (!p) { @@ -584,7 +584,7 @@ public: jsval dataVal[2]; dataVal[0] = OBJECT_TO_JSVAL(p->obj); - int arg1 = event; + int arg1 = (int)event; dataVal[1] = INT_TO_JSVAL(arg1); ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc));//, 2, dataVal); @@ -605,6 +605,7 @@ public: private: JSObject* _jsTarget; JSObject* _jsFunc; + bool _needUnroot; }; static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) @@ -622,7 +623,7 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex cocos2d::Object *arg0 = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, arg0); - int arg2; + Control::EventType arg2; ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); @@ -657,7 +658,7 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon obj = JSVAL_TO_OBJECT(argv[2]); JS_GET_NATIVE_PROXY(proxy, obj); - cocos2d::extension::ControlEvent *arg2 = (cocos2d::extension::ControlEvent *)(proxy ? proxy->ptr : NULL); + cocos2d::extension::Control::EventType *arg2 = (cocos2d::extension::Control::EventType *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, arg2); return JS_TRUE; From bf79a0560b0e16abc74dcdfca6571c9432579c7a Mon Sep 17 00:00:00 2001 From: minggo Date: Thu, 8 Aug 2013 16:31:44 +0800 Subject: [PATCH 3/9] issue #2462:use cocos2d-x c++ style --- cocos2dx/CCCamera.cpp | 12 +-- cocos2dx/CCCamera.h | 10 +- cocos2dx/CCConfiguration.cpp | 150 ++++++++++++++------------ cocos2dx/CCConfiguration.h | 46 ++++---- cocos2dx/CCDirector.cpp | 202 +++++++++++++++++------------------ cocos2dx/CCDirector.h | 66 ++++++------ 6 files changed, 248 insertions(+), 238 deletions(-) diff --git a/cocos2dx/CCCamera.cpp b/cocos2dx/CCCamera.cpp index b33c9dca6a..7c5965c1a3 100644 --- a/cocos2dx/CCCamera.cpp +++ b/cocos2dx/CCCamera.cpp @@ -65,7 +65,7 @@ void Camera::restore(void) _upY = 1.0f; _upZ = 0.0f; - kmMat4Identity( &_lookupMatrix ); + kmMat4Identity(&_lookupMatrix); _dirty = false; } @@ -76,15 +76,15 @@ void Camera::locate(void) { kmVec3 eye, center, up; - kmVec3Fill( &eye, _eyeX, _eyeY , _eyeZ ); - kmVec3Fill( ¢er, _centerX, _centerY, _centerZ ); + kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ); + kmVec3Fill(¢er, _centerX, _centerY, _centerZ); - kmVec3Fill( &up, _upX, _upY, _upZ); - kmMat4LookAt( &_lookupMatrix, &eye, ¢er, &up); + kmVec3Fill(&up, _upX, _upY, _upZ); + kmMat4LookAt(&_lookupMatrix, &eye, ¢er, &up); _dirty = false; } - kmGLMultMatrix( &_lookupMatrix ); + kmGLMultMatrix(&_lookupMatrix); } float Camera::getZEye(void) diff --git a/cocos2dx/CCCamera.h b/cocos2dx/CCCamera.h index 309d943a08..9030a1fb8b 100644 --- a/cocos2dx/CCCamera.h +++ b/cocos2dx/CCCamera.h @@ -24,13 +24,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __CCCAMERA_H__ -#define __CCCAMERA_H__ +#ifndef __COCOS2DX_CAMERA_H__ +#define __COCOS2DX_CAMERA_H__ + +#include #include "cocoa/CCObject.h" #include "ccMacros.h" #include "kazmath/mat4.h" -#include + NS_CC_BEGIN @@ -122,4 +124,4 @@ private: NS_CC_END -#endif // __CCCAMERA_H__ +#endif // __COCOS2DX_CAMERA_H__ diff --git a/cocos2dx/CCConfiguration.cpp b/cocos2dx/CCConfiguration.cpp index 93738a7ce3..15c219bbb8 100644 --- a/cocos2dx/CCConfiguration.cpp +++ b/cocos2dx/CCConfiguration.cpp @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ #include "CCConfiguration.h" +#include #include "ccMacros.h" #include "ccConfig.h" -#include #include "cocoa/CCDictionary.h" #include "cocoa/CCInteger.h" #include "cocoa/CCBool.h" @@ -38,9 +38,9 @@ using namespace std; NS_CC_BEGIN -Configuration* Configuration::s_gSharedConfiguration = NULL; +Configuration* Configuration::s_sharedConfiguration = nullptr; -Configuration::Configuration(void) +Configuration::Configuration() : _maxTextureSize(0) , _maxModelviewStackDepth(0) , _supportsPVRTC(false) @@ -51,40 +51,40 @@ Configuration::Configuration(void) , _supportsShareableVAO(false) , _maxSamplesAllowed(0) , _maxTextureUnits(0) -, _glExtensions(NULL) -, _valueDict(NULL) +, _glExtensions(nullptr) +, _valueDict(nullptr) { } -bool Configuration::init(void) +bool Configuration::init() { _valueDict = Dictionary::create(); _valueDict->retain(); - _valueDict->setObject( String::create( cocos2dVersion() ), "cocos2d.x.version"); + _valueDict->setObject(String::create( cocos2dVersion() ), "cocos2d.x.version"); #if CC_ENABLE_PROFILERS - _valueDict->setObject( Bool::create(true), "cocos2d.x.compiled_with_profiler"); + _valueDict->setObject(Bool::create(true), "cocos2d.x.compiled_with_profiler"); #else - _valueDict->setObject( Bool::create(false), "cocos2d.x.compiled_with_profiler"); + _valueDict->setObject(Bool::create(false), "cocos2d.x.compiled_with_profiler"); #endif #if CC_ENABLE_GL_STATE_CACHE == 0 - _valueDict->setObject( Bool::create(false), "cocos2d.x.compiled_with_gl_state_cache"); + _valueDict->setObject(Bool::create(false), "cocos2d.x.compiled_with_gl_state_cache"); #else - _valueDict->setObject( Bool::create(true), "cocos2d.x.compiled_with_gl_state_cache"); + _valueDict->setObject(Bool::create(true), "cocos2d.x.compiled_with_gl_state_cache"); #endif return true; } -Configuration::~Configuration(void) +Configuration::~Configuration() { _valueDict->release(); } -void Configuration::dumpInfo(void) const +void Configuration::dumpInfo() const { // Dump PrettyPrinter visitor(0); @@ -109,68 +109,68 @@ void Configuration::dumpInfo(void) const void Configuration::gatherGPUInfo() { - _valueDict->setObject( String::create( (const char*)glGetString(GL_VENDOR)), "gl.vendor"); - _valueDict->setObject( String::create( (const char*)glGetString(GL_RENDERER)), "gl.renderer"); - _valueDict->setObject( String::create( (const char*)glGetString(GL_VERSION)), "gl.version"); + _valueDict->setObject(String::create((const char*)glGetString(GL_VENDOR)), "gl.vendor"); + _valueDict->setObject(String::create((const char*)glGetString(GL_RENDERER)), "gl.renderer"); + _valueDict->setObject(String::create((const char*)glGetString(GL_VERSION)), "gl.version"); _glExtensions = (char *)glGetString(GL_EXTENSIONS); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &_maxTextureSize); - _valueDict->setObject( Integer::create((int)_maxTextureSize), "gl.max_texture_size"); + _valueDict->setObject(Integer::create((int)_maxTextureSize), "gl.max_texture_size"); glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &_maxTextureUnits); - _valueDict->setObject( Integer::create((int)_maxTextureUnits), "gl.max_texture_units"); + _valueDict->setObject(Integer::create((int)_maxTextureUnits), "gl.max_texture_units"); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) glGetIntegerv(GL_MAX_SAMPLES_APPLE, &_maxSamplesAllowed); - _valueDict->setObject( Integer::create((int)_maxSamplesAllowed), "gl.max_samples_allowed"); + _valueDict->setObject(Integer::create((int)_maxSamplesAllowed), "gl.max_samples_allowed"); #endif _supportsETC = checkForGLExtension("GL_OES_compressed_ETC1_RGB8_texture"); - _valueDict->setObject( Bool::create(_supportsETC), "gl.supports_ETC"); + _valueDict->setObject(Bool::create(_supportsETC), "gl.supports_ETC"); _supportsPVRTC = checkForGLExtension("GL_IMG_texture_compression_pvrtc"); - _valueDict->setObject( Bool::create(_supportsPVRTC), "gl.supports_PVRTC"); + _valueDict->setObject(Bool::create(_supportsPVRTC), "gl.supports_PVRTC"); _supportsNPOT = true; - _valueDict->setObject( Bool::create(_supportsNPOT), "gl.supports_NPOT"); + _valueDict->setObject(Bool::create(_supportsNPOT), "gl.supports_NPOT"); _supportsBGRA8888 = checkForGLExtension("GL_IMG_texture_format_BGRA888"); - _valueDict->setObject( Bool::create(_supportsBGRA8888), "gl.supports_BGRA8888"); + _valueDict->setObject(Bool::create(_supportsBGRA8888), "gl.supports_BGRA8888"); _supportsDiscardFramebuffer = checkForGLExtension("GL_EXT_discard_framebuffer"); - _valueDict->setObject( Bool::create(_supportsDiscardFramebuffer), "gl.supports_discard_framebuffer"); + _valueDict->setObject(Bool::create(_supportsDiscardFramebuffer), "gl.supports_discard_framebuffer"); _supportsShareableVAO = checkForGLExtension("vertex_array_object"); - _valueDict->setObject( Bool::create(_supportsShareableVAO), "gl.supports_vertex_array_object"); + _valueDict->setObject(Bool::create(_supportsShareableVAO), "gl.supports_vertex_array_object"); CHECK_GL_ERROR_DEBUG(); } Configuration* Configuration::getInstance() { - if (! s_gSharedConfiguration) + if (! s_sharedConfiguration) { - s_gSharedConfiguration = new Configuration(); - s_gSharedConfiguration->init(); + s_sharedConfiguration = new Configuration(); + s_sharedConfiguration->init(); } - return s_gSharedConfiguration; + return s_sharedConfiguration; } void Configuration::destroyInstance() { - CC_SAFE_RELEASE_NULL(s_gSharedConfiguration); + CC_SAFE_RELEASE_NULL(s_sharedConfiguration); } // XXX: deprecated -Configuration* Configuration::sharedConfiguration(void) +Configuration* Configuration::sharedConfiguration() { return Configuration::getInstance(); } // XXX: deprecated -void Configuration::purgeConfiguration(void) +void Configuration::purgeConfiguration() { Configuration::destroyInstance(); } @@ -178,43 +178,43 @@ void Configuration::purgeConfiguration(void) bool Configuration::checkForGLExtension(const string &searchName) const { - bool bRet = false; + bool ret = false; const char *kSearchName = searchName.c_str(); if (_glExtensions && strstr(_glExtensions, kSearchName)) { - bRet = true; + ret = true; } - return bRet; + return ret; } // // getters for specific variables. // Mantained for backward compatiblity reasons only. // -int Configuration::getMaxTextureSize(void) const +int Configuration::getMaxTextureSize() const { return _maxTextureSize; } -int Configuration::getMaxModelviewStackDepth(void) const +int Configuration::getMaxModelviewStackDepth() const { return _maxModelviewStackDepth; } -int Configuration::getMaxTextureUnits(void) const +int Configuration::getMaxTextureUnits() const { return _maxTextureUnits; } -bool Configuration::supportsNPOT(void) const +bool Configuration::supportsNPOT() const { return _supportsNPOT; } -bool Configuration::supportsPVRTC(void) const +bool Configuration::supportsPVRTC() const { return _supportsPVRTC; } @@ -229,17 +229,17 @@ bool Configuration::supportsETC() const #endif } -bool Configuration::supportsBGRA8888(void) const +bool Configuration::supportsBGRA8888() const { return _supportsBGRA8888; } -bool Configuration::supportsDiscardFramebuffer(void) const +bool Configuration::supportsDiscardFramebuffer() const { return _supportsDiscardFramebuffer; } -bool Configuration::supportsShareableVAO(void) const +bool Configuration::supportsShareableVAO() const { return _supportsShareableVAO; } @@ -247,63 +247,66 @@ bool Configuration::supportsShareableVAO(void) const // // generic getters for properties // -const char *Configuration::getCString( const char *key, const char *default_value ) const +const char *Configuration::getCString(const char *key, const char *defaultValue) const { Object *ret = _valueDict->objectForKey(key); - if( ret ) { - if( String *str=dynamic_cast(ret) ) + if (ret) + { + if (String *str=dynamic_cast(ret)) return str->getCString(); CCASSERT(false, "Key found, but from different type"); } // XXX: Should it throw an exception ? - return default_value; + return defaultValue; } /** returns the value of a given key as a boolean */ -bool Configuration::getBool( const char *key, bool default_value ) const +bool Configuration::getBool(const char *key, bool defaultValue) const { Object *ret = _valueDict->objectForKey(key); - if( ret ) { - if( Bool *boolobj=dynamic_cast(ret) ) + if (ret) + { + if (Bool *boolobj=dynamic_cast(ret)) return boolobj->getValue(); - if( String *strobj=dynamic_cast(ret) ) + if (String *strobj=dynamic_cast(ret)) return strobj->boolValue(); CCASSERT(false, "Key found, but from different type"); } // XXX: Should it throw an exception ? - return default_value; + return defaultValue; } /** returns the value of a given key as a double */ -double Configuration::getNumber( const char *key, double default_value ) const +double Configuration::getNumber( const char *key, double defaultValue ) const { Object *ret = _valueDict->objectForKey(key); - if( ret ) { - if( Double *obj=dynamic_cast(ret) ) + if( ret ) + { + if (Double *obj=dynamic_cast(ret)) return obj->getValue(); - if( Integer *obj=dynamic_cast(ret) ) + if (Integer *obj=dynamic_cast(ret)) return obj->getValue(); - if( String *strobj=dynamic_cast(ret) ) + if (String *strobj=dynamic_cast(ret)) return strobj->doubleValue(); CCASSERT(false, "Key found, but from different type"); } // XXX: Should it throw an exception ? - return default_value; + return defaultValue; } -Object * Configuration::getObject( const char *key ) const +Object * Configuration::getObject(const char *key) const { return _valueDict->objectForKey(key); } -void Configuration::setObject( const char *key, Object *value ) +void Configuration::setObject(const char *key, Object *value) { _valueDict->setObject(value, key); } @@ -312,35 +315,40 @@ void Configuration::setObject( const char *key, Object *value ) // // load file // -void Configuration::loadConfigFile( const char *filename ) +void Configuration::loadConfigFile(const char *filename) { Dictionary *dict = Dictionary::createWithContentsOfFile(filename); CCASSERT(dict, "cannot create dictionary"); // search for metadata - bool metadata_ok = false; + bool validMetadata = false; Object *metadata = dict->objectForKey("metadata"); - if( metadata && dynamic_cast(metadata) ) { + if (metadata && dynamic_cast(metadata)) + { Object *format_o = static_cast(metadata)->objectForKey("format"); // XXX: cocos2d-x returns Strings when importing from .plist. This bug will be addressed in cocos2d-x v3.x - if( format_o && dynamic_cast(format_o) ) { + if (format_o && dynamic_cast(format_o)) + { int format = static_cast(format_o)->intValue(); // Support format: 1 - if( format == 1 ) { - metadata_ok = true; + if (format == 1) + { + validMetadata = true; } } } - if( ! metadata_ok ) { + if (! validMetadata) + { CCLOG("Invalid config format for file: %s", filename); return; } Object *data = dict->objectForKey("data"); - if( !data || !dynamic_cast(data) ) { + if (!data || !dynamic_cast(data)) + { CCLOG("Expected 'data' dict, but not found. Config file: %s", filename); return; } @@ -350,10 +358,10 @@ void Configuration::loadConfigFile( const char *filename ) DictElement* element; CCDICT_FOREACH(data_dict, element) { - if( ! _valueDict->objectForKey( element->getStrKey() ) ) - _valueDict->setObject(element->getObject(), element->getStrKey() ); + if(! _valueDict->objectForKey( element->getStrKey() )) + _valueDict->setObject(element->getObject(), element->getStrKey()); else - CCLOG("Key already present. Ignoring '%s'", element->getStrKey() ); + CCLOG("Key already present. Ignoring '%s'", element->getStrKey()); } } diff --git a/cocos2dx/CCConfiguration.h b/cocos2dx/CCConfiguration.h index 86c296d9e0..c5bb82060a 100644 --- a/cocos2dx/CCConfiguration.h +++ b/cocos2dx/CCConfiguration.h @@ -54,90 +54,90 @@ public: static void destroyInstance(); /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static Configuration *sharedConfiguration(void); + CC_DEPRECATED_ATTRIBUTE static Configuration *sharedConfiguration(); /** @deprecated Use destroyInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static void purgeConfiguration(void); + CC_DEPRECATED_ATTRIBUTE static void purgeConfiguration(); public: - virtual ~Configuration(void); + virtual ~Configuration(); /** OpenGL Max texture size. */ - int getMaxTextureSize(void) const; + int getMaxTextureSize() const; /** OpenGL Max Modelview Stack Depth. */ - int getMaxModelviewStackDepth(void) const; + int getMaxModelviewStackDepth() const; /** returns the maximum texture units @since v2.0.0 */ - int getMaxTextureUnits(void) const; + int getMaxTextureUnits() const; /** Whether or not the GPU supports NPOT (Non Power Of Two) textures. OpenGL ES 2.0 already supports NPOT (iOS). @since v0.99.2 */ - bool supportsNPOT(void) const; + bool supportsNPOT() const; /** Whether or not PVR Texture Compressed is supported */ - bool supportsPVRTC(void) const; + bool supportsPVRTC() const; /** Whether or not ETC Texture Compressed is supported */ - bool supportsETC(void) const; + bool supportsETC() const; /** Whether or not BGRA8888 textures are supported. @since v0.99.2 */ - bool supportsBGRA8888(void) const; + bool supportsBGRA8888() const; /** Whether or not glDiscardFramebufferEXT is supported @since v0.99.2 */ - bool supportsDiscardFramebuffer(void) const; + bool supportsDiscardFramebuffer() const; /** Whether or not shareable VAOs are supported. @since v2.0.0 */ - bool supportsShareableVAO(void) const; + bool supportsShareableVAO() const; /** returns whether or not an OpenGL is supported */ bool checkForGLExtension(const std::string &searchName) const; - bool init(void); + bool init(); /** returns the value of a given key as a string. If the key is not found, it will return the default value */ - const char* getCString( const char *key, const char *default_value=NULL ) const; + const char* getCString(const char *key, const char *defaultValue = nullptr) const; /** returns the value of a given key as a boolean. If the key is not found, it will return the default value */ - bool getBool( const char *key, bool default_value=false ) const; + bool getBool(const char *key, bool defaultValue = false) const; /** returns the value of a given key as a double. If the key is not found, it will return the default value */ - double getNumber( const char *key, double default_value=0.0 ) const; + double getNumber(const char *key, double defaultValue = 0.0) const; /** returns the value of a given key as a double */ - Object * getObject( const char *key ) const; + Object * getObject(const char *key) const; /** sets a new key/value pair in the configuration dictionary */ - void setObject( const char *key, Object *value ); + void setObject(const char *key, Object *value); /** dumps the current configuration on the console */ - void dumpInfo(void) const; + void dumpInfo() const; /** gathers OpenGL / GPU information */ - void gatherGPUInfo( void ); + void gatherGPUInfo(); /** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */ - void loadConfigFile( const char *filename ); + void loadConfigFile(const char *filename); private: Configuration(void); - static Configuration *s_gSharedConfiguration; - static std::string s_sConfigfile; + static Configuration *s_sharedConfiguration; + static std::string s_configfile; protected: GLint _maxTextureSize; diff --git a/cocos2dx/CCDirector.cpp b/cocos2dx/CCDirector.cpp index 75a46757fb..4de921cdd8 100644 --- a/cocos2dx/CCDirector.cpp +++ b/cocos2dx/CCDirector.cpp @@ -83,7 +83,7 @@ NS_CC_BEGIN // XXX it should be a Director ivar. Move it there once support for multiple directors is added // singleton stuff -static DisplayLinkDirector *s_SharedDirector = NULL; +static DisplayLinkDirector *s_SharedDirector = nullptr; #define kDefaultFPS 60 // 60 frames per second extern const char* cocos2dVersion(void); @@ -109,23 +109,23 @@ bool Director::init(void) setDefaultValues(); // scenes - _runningScene = NULL; - _nextScene = NULL; + _runningScene = nullptr; + _nextScene = nullptr; - _notificationNode = NULL; + _notificationNode = nullptr; _scenesStack = new Array(); _scenesStack->init(); // projection delegate if "Custom" projection is used - _projectionDelegate = NULL; + _projectionDelegate = nullptr; // FPS _accumDt = 0.0f; _frameRate = 0.0f; - _FPSLabel = NULL; - _SPFLabel = NULL; - _drawsLabel = NULL; + _FPSLabel = nullptr; + _SPFLabel = nullptr; + _drawsLabel = nullptr; _totalFrames = _frames = 0; _FPS = new char[10]; _lastUpdate = new struct timeval; @@ -138,7 +138,7 @@ bool Director::init(void) _winSizeInPoints = Size::ZERO; - _openGLView = NULL; + _openGLView = nullptr; _contentScaleFactor = 1.0f; @@ -193,7 +193,7 @@ Director::~Director(void) // delete fps string delete []_FPS; - s_SharedDirector = NULL; + s_SharedDirector = nullptr; } void Director::setDefaultValues(void) @@ -209,7 +209,7 @@ void Director::setDefaultValues(void) // GL projection const char *projection = conf->getCString("cocos2d.x.gl.projection", "2d"); - if( strcmp(projection, "3d") == 0 ) + if (strcmp(projection, "3d") == 0) _projection = Projection::_3D; else if (strcmp(projection, "2d") == 0) _projection = Projection::_2D; @@ -220,11 +220,11 @@ void Director::setDefaultValues(void) // Default pixel format for PNG images with alpha const char *pixel_format = conf->getCString("cocos2d.x.texture.pixel_format_for_png", "rgba8888"); - if( strcmp(pixel_format, "rgba8888") == 0 ) + if (strcmp(pixel_format, "rgba8888") == 0) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - else if( strcmp(pixel_format, "rgba4444") == 0 ) + else if(strcmp(pixel_format, "rgba4444") == 0) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - else if( strcmp(pixel_format, "rgba5551") == 0 ) + else if(strcmp(pixel_format, "rgba5551") == 0) Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1); // PVR v2 has alpha premultiplied ? @@ -232,7 +232,7 @@ void Director::setDefaultValues(void) Texture2D::PVRImagesHavePremultipliedAlpha(pvr_alpha_premultipled); } -void Director::setGLDefaultValues(void) +void Director::setGLDefaultValues() { // This method SHOULD be called only after openGLView_ was initialized CCASSERT(_openGLView, "opengl view should not be null"); @@ -248,7 +248,7 @@ void Director::setGLDefaultValues(void) } // Draw the Scene -void Director::drawScene(void) +void Director::drawScene() { // calculate "global" dt calculateDeltaTime(); @@ -308,11 +308,11 @@ void Director::drawScene(void) } } -void Director::calculateDeltaTime(void) +void Director::calculateDeltaTime() { struct timeval now; - if (gettimeofday(&now, NULL) != 0) + if (gettimeofday(&now, nullptr) != 0) { CCLOG("error in gettimeofday"); _deltaTime = 0; @@ -333,7 +333,7 @@ void Director::calculateDeltaTime(void) #ifdef DEBUG // If we are debugging our code, prevent big delta time - if(_deltaTime > 0.2f) + if (_deltaTime > 0.2f) { _deltaTime = 1 / 60.0f; } @@ -402,7 +402,7 @@ void Director::setProjection(Projection projection) kmGLMatrixMode(KM_GL_PROJECTION); kmGLLoadIdentity(); kmMat4 orthoMatrix; - kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024 ); + kmMat4OrthographicProjection(&orthoMatrix, 0, size.width, 0, size.height, -1024, 1024); kmGLMultMatrix(&orthoMatrix); kmGLMatrixMode(KM_GL_MODELVIEW); kmGLLoadIdentity(); @@ -418,7 +418,7 @@ void Director::setProjection(Projection projection) kmGLLoadIdentity(); // issue #1334 - kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, zeye*2); + kmMat4PerspectiveProjection(&matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, zeye*2); // kmMat4PerspectiveProjection( &matrixPerspective, 60, (GLfloat)size.width/size.height, 0.1f, 1500); kmGLMultMatrix(&matrixPerspective); @@ -426,9 +426,9 @@ void Director::setProjection(Projection projection) kmGLMatrixMode(KM_GL_MODELVIEW); kmGLLoadIdentity(); kmVec3 eye, center, up; - kmVec3Fill( &eye, size.width/2, size.height/2, zeye ); - kmVec3Fill( ¢er, size.width/2, size.height/2, 0.0f ); - kmVec3Fill( &up, 0.0f, 1.0f, 0.0f); + kmVec3Fill(&eye, size.width/2, size.height/2, zeye); + kmVec3Fill(¢er, size.width/2, size.height/2, 0.0f); + kmVec3Fill(&up, 0.0f, 1.0f, 0.0f); kmMat4LookAt(&matrixLookup, &eye, ¢er, &up); kmGLMultMatrix(&matrixLookup); break; @@ -437,6 +437,7 @@ void Director::setProjection(Projection projection) case Projection::CUSTOM: if (_projectionDelegate) _projectionDelegate->updateProjection(); + break; default: @@ -464,9 +465,9 @@ float Director::getZEye(void) const return (_winSizeInPoints.height / 1.1566f); } -void Director::setAlphaBlending(bool bOn) +void Director::setAlphaBlending(bool on) { - if (bOn) + if (on) { GL::blendFunc(CC_BLEND_SRC, CC_BLEND_DST); } @@ -478,9 +479,9 @@ void Director::setAlphaBlending(bool bOn) CHECK_GL_ERROR_DEBUG(); } -void Director::setDepthTest(bool bOn) +void Director::setDepthTest(bool on) { - if (bOn) + if (on) { glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); @@ -494,8 +495,7 @@ void Director::setDepthTest(bool bOn) CHECK_GL_ERROR_DEBUG(); } -static void -GLToClipTransform(kmMat4 *transformOut) +static void GLToClipTransform(kmMat4 *transformOut) { kmMat4 projection; kmGLGetMatrix(KM_GL_PROJECTION, &projection); @@ -576,41 +576,41 @@ Point Director::getVisibleOrigin() const // scene management -void Director::runWithScene(Scene *pScene) +void Director::runWithScene(Scene *scene) { - CCASSERT(pScene != NULL, "This command can only be used to start the Director. There is already a scene present."); - CCASSERT(_runningScene == NULL, "_runningScene should be null"); + CCASSERT(scene != nullptr, "This command can only be used to start the Director. There is already a scene present."); + CCASSERT(_runningScene == nullptr, "_runningScene should be null"); - pushScene(pScene); + pushScene(scene); startAnimation(); } -void Director::replaceScene(Scene *pScene) +void Director::replaceScene(Scene *scene) { CCASSERT(_runningScene, "Use runWithScene: instead to start the director"); - CCASSERT(pScene != NULL, "the scene should not be null"); + CCASSERT(scene != nullptr, "the scene should not be null"); unsigned int index = _scenesStack->count(); _sendCleanupToScene = true; - _scenesStack->replaceObjectAtIndex(index - 1, pScene); + _scenesStack->replaceObjectAtIndex(index - 1, scene); - _nextScene = pScene; + _nextScene = scene; } -void Director::pushScene(Scene *pScene) +void Director::pushScene(Scene *scene) { - CCASSERT(pScene, "the scene should not null"); + CCASSERT(scene, "the scene should not null"); _sendCleanupToScene = false; - _scenesStack->addObject(pScene); - _nextScene = pScene; + _scenesStack->addObject(scene); + _nextScene = scene; } void Director::popScene(void) { - CCASSERT(_runningScene != NULL, "running scene should not null"); + CCASSERT(_runningScene != nullptr, "running scene should not null"); _scenesStack->removeLastObject(); unsigned int c = _scenesStack->count(); @@ -633,8 +633,8 @@ void Director::popToRootScene(void) void Director::popToSceneStackLevel(int level) { - CCASSERT(_runningScene != NULL, "A running Scene is needed"); - int c = (int)_scenesStack->count(); + CCASSERT(_runningScene != nullptr, "A running Scene is needed"); + int c = static_cast(_scenesStack->count()); // level 0? -> end if (level == 0) @@ -660,7 +660,7 @@ void Director::popToSceneStackLevel(int level) current->cleanup(); _scenesStack->removeLastObject(); - c--; + --c; } _nextScene = (Scene*)_scenesStack->lastObject(); @@ -689,8 +689,8 @@ void Director::purgeDirector() _runningScene->release(); } - _runningScene = NULL; - _nextScene = NULL; + _runningScene = nullptr; + _nextScene = nullptr; // remove all objects, but don't release it. // runWithScene might be executed after 'end'. @@ -724,16 +724,16 @@ void Director::purgeDirector() // OpenGL view _openGLView->end(); - _openGLView = NULL; + _openGLView = nullptr; // delete Director release(); } -void Director::setNextScene(void) +void Director::setNextScene() { - bool runningIsTransition = dynamic_cast(_runningScene) != NULL; - bool newIsTransition = dynamic_cast(_nextScene) != NULL; + bool runningIsTransition = dynamic_cast(_runningScene) != nullptr; + bool newIsTransition = dynamic_cast(_nextScene) != nullptr; // If it is not a transition, call onExit/cleanup if (! newIsTransition) @@ -758,7 +758,7 @@ void Director::setNextScene(void) } _runningScene = _nextScene; _nextScene->retain(); - _nextScene = NULL; + _nextScene = nullptr; if ((! runningIsTransition) && _runningScene) { @@ -767,7 +767,7 @@ void Director::setNextScene(void) } } -void Director::pause(void) +void Director::pause() { if (_paused) { @@ -781,7 +781,7 @@ void Director::pause(void) _paused = true; } -void Director::resume(void) +void Director::resume() { if (! _paused) { @@ -790,7 +790,7 @@ void Director::resume(void) setAnimationInterval(_oldAnimationInterval); - if (gettimeofday(_lastUpdate, NULL) != 0) + if (gettimeofday(_lastUpdate, nullptr) != 0) { CCLOG("cocos2d: Director: Error in gettimeofday"); } @@ -801,9 +801,9 @@ void Director::resume(void) // display the FPS using a LabelAtlas // updates the FPS every frame -void Director::showStats(void) +void Director::showStats() { - _frames++; + ++_frames; _accumDt += _deltaTime; if (_displayStats) @@ -838,7 +838,7 @@ void Director::showStats(void) void Director::calculateMPF() { struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); _secondsPerFrame = (now.tv_sec - _lastUpdate->tv_sec) + (now.tv_usec - _lastUpdate->tv_usec) / 1000000.0f; } @@ -853,10 +853,10 @@ void Director::getFPSImageData(unsigned char** datapointer, unsigned int* length void Director::createStatsLabel() { - Texture2D *texture = NULL; + Texture2D *texture = nullptr; TextureCache *textureCache = TextureCache::getInstance(); - if( _FPSLabel && _SPFLabel ) + if (_FPSLabel && _SPFLabel) { CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_SPFLabel); @@ -867,13 +867,13 @@ void Director::createStatsLabel() Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - unsigned char *data = NULL; - unsigned int data_len = 0; - getFPSImageData(&data, &data_len); + unsigned char *data = nullptr; + unsigned int dataLength = 0; + getFPSImageData(&data, &dataLength); Image* image = new Image(); - bool isOK = image->initWithImageData(data, data_len); - if (!isOK) { + bool isOK = image->initWithImageData(data, dataLength); + if (! isOK) { CCLOGERROR("%s", "Fails: init fps_images"); return; } @@ -918,7 +918,7 @@ void Director::createStatsLabel() _FPSLabel->setPosition(CC_DIRECTOR_STATS_POSITION); } -float Director::getContentScaleFactor(void) const +float Director::getContentScaleFactor() const { return _contentScaleFactor; } @@ -949,18 +949,18 @@ DirectorDelegate* Director::getDelegate() const return _projectionDelegate; } -void Director::setDelegate(DirectorDelegate* pDelegate) +void Director::setDelegate(DirectorDelegate* delegate) { - _projectionDelegate = pDelegate; + _projectionDelegate = delegate; } -void Director::setScheduler(Scheduler* pScheduler) +void Director::setScheduler(Scheduler* scheduler) { - if (_scheduler != pScheduler) + if (_scheduler != scheduler) { - CC_SAFE_RETAIN(pScheduler); + CC_SAFE_RETAIN(scheduler); CC_SAFE_RELEASE(_scheduler); - _scheduler = pScheduler; + _scheduler = scheduler; } } @@ -969,13 +969,13 @@ Scheduler* Director::getScheduler() const return _scheduler; } -void Director::setActionManager(ActionManager* pActionManager) +void Director::setActionManager(ActionManager* actionManager) { - if (_actionManager != pActionManager) + if (_actionManager != actionManager) { - CC_SAFE_RETAIN(pActionManager); + CC_SAFE_RETAIN(actionManager); CC_SAFE_RELEASE(_actionManager); - _actionManager = pActionManager; + _actionManager = actionManager; } } @@ -984,13 +984,13 @@ ActionManager* Director::getActionManager() const return _actionManager; } -void Director::setTouchDispatcher(TouchDispatcher* pTouchDispatcher) +void Director::setTouchDispatcher(TouchDispatcher* touchDispatcher) { - if (_touchDispatcher != pTouchDispatcher) + if (_touchDispatcher != touchDispatcher) { - CC_SAFE_RETAIN(pTouchDispatcher); + CC_SAFE_RETAIN(touchDispatcher); CC_SAFE_RELEASE(_touchDispatcher); - _touchDispatcher = pTouchDispatcher; + _touchDispatcher = touchDispatcher; } } @@ -999,11 +999,11 @@ TouchDispatcher* Director::getTouchDispatcher() const return _touchDispatcher; } -void Director::setKeyboardDispatcher(KeyboardDispatcher* pKeyboardDispatcher) +void Director::setKeyboardDispatcher(KeyboardDispatcher* keyboardDispatcher) { - CC_SAFE_RETAIN(pKeyboardDispatcher); + CC_SAFE_RETAIN(keyboardDispatcher); CC_SAFE_RELEASE(_keyboardDispatcher); - _keyboardDispatcher = pKeyboardDispatcher; + _keyboardDispatcher = keyboardDispatcher; } KeyboardDispatcher* Director::getKeyboardDispatcher() const @@ -1011,11 +1011,11 @@ KeyboardDispatcher* Director::getKeyboardDispatcher() const return _keyboardDispatcher; } -void Director::setKeypadDispatcher(KeypadDispatcher* pKeypadDispatcher) +void Director::setKeypadDispatcher(KeypadDispatcher* keyboardDispatcher) { - CC_SAFE_RETAIN(pKeypadDispatcher); + CC_SAFE_RETAIN(keyboardDispatcher); CC_SAFE_RELEASE(_keypadDispatcher); - _keypadDispatcher = pKeypadDispatcher; + _keypadDispatcher = keyboardDispatcher; } KeypadDispatcher* Director::getKeypadDispatcher() const @@ -1023,12 +1023,12 @@ KeypadDispatcher* Director::getKeypadDispatcher() const return _keypadDispatcher; } -void Director::setAccelerometer(Accelerometer* pAccelerometer) +void Director::setAccelerometer(Accelerometer* accelerometer) { - if (_accelerometer != pAccelerometer) + if (_accelerometer != accelerometer) { CC_SAFE_DELETE(_accelerometer); - _accelerometer = pAccelerometer; + _accelerometer = accelerometer; } } @@ -1044,9 +1044,9 @@ Accelerometer* Director::getAccelerometer() const // should we implement 4 types of director ?? // I think DisplayLinkDirector is enough // so we now only support DisplayLinkDirector -void DisplayLinkDirector::startAnimation(void) +void DisplayLinkDirector::startAnimation() { - if (gettimeofday(_lastUpdate, NULL) != 0) + if (gettimeofday(_lastUpdate, nullptr) != 0) { CCLOG("cocos2d: DisplayLinkDirector: Error on gettimeofday"); } @@ -1057,7 +1057,7 @@ void DisplayLinkDirector::startAnimation(void) #endif // EMSCRIPTEN } -void DisplayLinkDirector::mainLoop(void) +void DisplayLinkDirector::mainLoop() { if (_purgeDirecotorInNextLoop) { @@ -1065,22 +1065,22 @@ void DisplayLinkDirector::mainLoop(void) purgeDirector(); } else if (! _invalid) - { - drawScene(); + { + drawScene(); - // release the objects - PoolManager::sharedPoolManager()->pop(); - } + // release the objects + PoolManager::sharedPoolManager()->pop(); + } } -void DisplayLinkDirector::stopAnimation(void) +void DisplayLinkDirector::stopAnimation() { _invalid = true; } -void DisplayLinkDirector::setAnimationInterval(double dValue) +void DisplayLinkDirector::setAnimationInterval(double value) { - _animationInterval = dValue; + _animationInterval = value; if (! _invalid) { stopAnimation(); diff --git a/cocos2dx/CCDirector.h b/cocos2dx/CCDirector.h index d903d46afb..4001f82804 100644 --- a/cocos2dx/CCDirector.h +++ b/cocos2dx/CCDirector.h @@ -117,15 +117,15 @@ public: // attribute /** Get current running Scene. Director can only run one Scene at the time */ - inline Scene* getRunningScene(void) { return _runningScene; } + inline Scene* getRunningScene() { return _runningScene; } /** Get the FPS value */ - inline double getAnimationInterval(void) { return _animationInterval; } + inline double getAnimationInterval() { return _animationInterval; } /** Set the FPS value. */ virtual void setAnimationInterval(double dValue) = 0; /** Whether or not to display the FPS on the bottom-left corner */ - inline bool isDisplayStats(void) { return _displayStats; } + inline bool isDisplayStats() { return _displayStats; } /** Display the FPS on the bottom-left corner */ inline void setDisplayStats(bool displayStats) { _displayStats = displayStats; } @@ -133,22 +133,22 @@ public: inline float getSecondsPerFrame() { return _secondsPerFrame; } /** Get the EGLView, where everything is rendered */ - inline EGLView* getOpenGLView(void) { return _openGLView; } + inline EGLView* getOpenGLView() { return _openGLView; } void setOpenGLView(EGLView *pobOpenGLView); - inline bool isNextDeltaTimeZero(void) { return _nextDeltaTimeZero; } + inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; } void setNextDeltaTimeZero(bool nextDeltaTimeZero); /** Whether or not the Director is paused */ - inline bool isPaused(void) { return _paused; } + inline bool isPaused() { return _paused; } /** How many frames were called since the director started */ - inline unsigned int getTotalFrames(void) { return _totalFrames; } + inline unsigned int getTotalFrames() { return _totalFrames; } /** Sets an OpenGL projection @since v0.8.2 */ - inline Projection getProjection(void) { return _projection; } + inline Projection getProjection() { return _projection; } void setProjection(Projection projection); /** Sets the glViewport*/ @@ -162,7 +162,7 @@ public: If the new scene replaces the old one, the it will receive the "cleanup" message. @since v0.99.0 */ - inline bool isSendCleanupToScene(void) { return _sendCleanupToScene; } + inline bool isSendCleanupToScene() { return _sendCleanupToScene; } /** This object will be visited after the main scene is visited. This object MUST implement the "visit" selector. @@ -176,17 +176,17 @@ public: @since v0.99.5 */ DirectorDelegate* getDelegate() const; - void setDelegate(DirectorDelegate* pDelegate); + void setDelegate(DirectorDelegate* delegate); // window size /** returns the size of the OpenGL view in points. */ - const Size& getWinSize(void) const; + const Size& getWinSize() const; /** returns the size of the OpenGL view in pixels. */ - Size getWinSizeInPixels(void) const; + Size getWinSizeInPixels() const; /** returns visible size of the OpenGL view in points. * the value is equal to getWinSize if don't invoke @@ -209,7 +209,7 @@ public: Point convertToUI(const Point& point); /// XXX: missing description - float getZEye(void) const; + float getZEye() const; // Scene Management @@ -233,13 +233,13 @@ public: * The running scene will be deleted. If there are no more scenes in the stack the execution is terminated. * ONLY call it if there is a running scene. */ - void popScene(void); + void popScene(); /** Pops out all scenes from the queue until the root scene in the queue. * This scene will replace the running one. * Internally it will call `popToSceneStackLevel(1)` */ - void popToRootScene(void); + void popToRootScene(); /** Pops out all scenes from the queue until it reaches `level`. If level is 0, it will end the director. @@ -256,35 +256,35 @@ public: /** Ends the execution, releases the running scene. It doesn't remove the OpenGL view from its parent. You have to do it manually. */ - void end(void); + void end(); /** Pauses the running scene. The running scene will be _drawed_ but all scheduled timers will be paused While paused, the draw rate will be 4 FPS to reduce CPU consumption */ - void pause(void); + void pause(); /** Resumes the paused scene The scheduled timers will be activated again. The "delta time" will be 0 (as if the game wasn't paused) */ - void resume(void); + void resume(); /** Stops the animation. Nothing will be drawn. The main loop won't be triggered anymore. If you don't want to pause your animation call [pause] instead. */ - virtual void stopAnimation(void) = 0; + virtual void stopAnimation() = 0; /** The main loop is triggered again. Call this function only if [stopAnimation] was called earlier @warning Don't call this function to start the main loop. To run the main loop call runWithScene */ - virtual void startAnimation(void) = 0; + virtual void startAnimation() = 0; /** Draw the scene. This method is called every frame. Don't call it manually. */ - void drawScene(void); + void drawScene(); // Memory Helper @@ -292,23 +292,23 @@ public: It will purge the TextureCache, SpriteFrameCache, LabelBMFont cache @since v0.99.3 */ - void purgeCachedData(void); + void purgeCachedData(); /** sets the default values based on the Configuration info */ - void setDefaultValues(void); + void setDefaultValues(); // OpenGL Helper /** sets the OpenGL default values */ - void setGLDefaultValues(void); + void setGLDefaultValues(); /** enables/disables OpenGL alpha blending */ - void setAlphaBlending(bool bOn); + void setAlphaBlending(bool on); /** enables/disables OpenGL depth test */ - void setDepthTest(bool bOn); + void setDepthTest(bool on); - virtual void mainLoop(void) = 0; + virtual void mainLoop() = 0; /** The size in pixels of the surface. It could be different than the screen size. High-res devices might have a higher surface size than the screen size. @@ -316,7 +316,7 @@ public: @since v0.99.4 */ void setContentScaleFactor(float scaleFactor); - float getContentScaleFactor(void) const; + float getContentScaleFactor() const; public: /** Gets the Scheduler associated with this director @@ -388,7 +388,7 @@ protected: void purgeDirector(); bool _purgeDirecotorInNextLoop; // this flag will be set to true in end() - void setNextScene(void); + void setNextScene(); void showStats(); void createStatsLabel(); @@ -511,16 +511,16 @@ protected: class DisplayLinkDirector : public Director { public: - DisplayLinkDirector(void) + DisplayLinkDirector() : _invalid(false) {} // // Overrides // - virtual void mainLoop(void) override; - virtual void setAnimationInterval(double dValue) override; - virtual void startAnimation(void) override; + virtual void mainLoop() override; + virtual void setAnimationInterval(double value) override; + virtual void startAnimation() override; virtual void stopAnimation() override; protected: From fc437c5ef496086c966de2811cb5ebb9b3feebe0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 10:56:39 +0800 Subject: [PATCH 4/9] (Array*) --> static_cast() for CCControl.cpp. --- extensions/GUI/CCControlExtension/CCControl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 03aeab0594..2d43412907 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -267,7 +267,7 @@ bool Control::isTouchInside(Touch* touch) Array* Control::dispatchListforControlEvent(EventType controlEvent) { - Array* invocationList = (Array*)_dispatchTable->objectForKey((int)controlEvent); + Array* invocationList = static_cast(_dispatchTable->objectForKey((int)controlEvent)); // If the invocation list does not exist for the dispatch table, we create it if (invocationList == NULL) From f527387b1e6df9aca7d6a57d3276995baf7277a1 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 10:58:25 +0800 Subject: [PATCH 5/9] closed #1690: Exposing 'cc.Control. addTargetWithActionForControlEvents' and 'cc.Control.removeTargetWithActionForControlEvents' to JS. --- .../javascript/bindings/ScriptingCore.cpp | 16 ++- .../jsb_cocos2dx_extension_manual.cpp | 135 ++++++++++++++---- 2 files changed, 125 insertions(+), 26 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index 92edcecdc0..b69ad854ef 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -174,8 +174,20 @@ void ScriptingCore::executeJSFunctionWithThisObj(jsval thisObj, jsval* vp/* = NULL*/, jsval* retVal/* = NULL*/) { - if(callback != JSVAL_VOID || thisObj != JSVAL_VOID) { - JS_CallFunctionValue(cx_, JSVAL_TO_OBJECT(thisObj), callback, argc, vp, retVal); + if(callback != JSVAL_VOID || thisObj != JSVAL_VOID) + { + // Very important: The last parameter 'retVal' passed to 'JS_CallFunctionValue' should not be a NULL pointer. + // If it's a NULL pointer, crash will be triggered in 'JS_CallFunctionValue'. To find out the reason of this crash is very difficult. + // So we have to check the availability of 'retVal'. + if (retVal) + { + JS_CallFunctionValue(cx_, JSVAL_TO_OBJECT(thisObj), callback, argc, vp, retVal); + } + else + { + jsval jsRet; + JS_CallFunctionValue(cx_, JSVAL_TO_OBJECT(thisObj), callback, argc, vp, &jsRet); + } } } diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 39109e34c8..79838de1da 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -572,9 +572,37 @@ static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, js return JS_FALSE; } -class JSB_ControlButtonTarget : public Object { + + +class JSB_ControlButtonTarget : public Object +{ public: - virtual void onEvent(Object *controlButton, Control::EventType event) { + JSB_ControlButtonTarget() + {} + + virtual ~JSB_ControlButtonTarget() + { + CCLOGINFO("In the destruction of JSB_ControlButtonTarget ..."); + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + if (_needUnroot) + { + JS_RemoveObjectRoot(cx, &_jsTarget); + } + + JS_RemoveObjectRoot(cx, &_jsFunc); + + for (auto iter = _jsNativeTargetMap.begin(); iter != _jsNativeTargetMap.end(); ++iter) + { + if (this == iter->second) + { + _jsNativeTargetMap.erase(iter); + break; + } + } + } + + virtual void onEvent(Object *controlButton, Control::EventType event) + { js_proxy_t * p; JS_GET_PROXY(p, controlButton); if (!p) { @@ -586,54 +614,100 @@ public: dataVal[0] = OBJECT_TO_JSVAL(p->obj); int arg1 = (int)event; dataVal[1] = INT_TO_JSVAL(arg1); - - ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc));//, 2, dataVal); + jsval jsRet; + + ScriptingCore::getInstance()->executeJSFunctionWithThisObj(OBJECT_TO_JSVAL(_jsTarget), OBJECT_TO_JSVAL(_jsFunc), 2, dataVal, &jsRet); } void setJSTarget(JSObject* pJSTarget) { _jsTarget = pJSTarget; - JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_jsTarget, "JSB_ControlButtonTarget"); + + js_proxy_t* p = jsb_get_js_proxy(_jsTarget); + if (!p) + { + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); + JS_AddNamedObjectRoot(cx, &_jsTarget, "JSB_ControlButtonTarget, target"); + _needUnroot = true; + } } - void setJSAction(JSObject* jsFunc) { + void setJSAction(JSObject* jsFunc) + { _jsFunc = jsFunc; + JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JS_AddNamedObjectRoot(cx, &_jsFunc, "JSB_ControlButtonTarget"); + JS_AddNamedObjectRoot(cx, &_jsFunc, "JSB_ControlButtonTarget, func"); } + + void setEventType(Control::EventType type) + { + _type = type; + } +public: + + static std::multimap _jsNativeTargetMap; + JSObject* _jsFunc; + Control::EventType _type; private: JSObject* _jsTarget; - JSObject* _jsFunc; bool _needUnroot; }; +std::multimap JSB_ControlButtonTarget::_jsNativeTargetMap; + static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy; JS_GET_NATIVE_PROXY(proxy, obj); + js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); JSBool ok = JS_TRUE; if (argc == 3) { - JSObject *tmpObj = JSVAL_TO_OBJECT(argv[0]); - JS_GET_NATIVE_PROXY(proxy, tmpObj); - cocos2d::Object *arg0 = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg0); + JSObject* jsDelegate = JSVAL_TO_OBJECT(argv[0]); + JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); Control::EventType arg2; ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); + // Check whether the target already exists. + auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(jsDelegate); + for (auto it=range.first; it!=range.second; ++it) + { + if (it->second->_jsFunc == jsFunc && arg2 == it->second->_type) + { + // Return true directly. + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_TRUE; + } + } + // save the delegate - JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSB_ControlButtonTarget* nativeDelegate = new JSB_ControlButtonTarget(); + nativeDelegate->setJSTarget(jsDelegate); - nativeDelegate->setJSAction(JSVAL_TO_OBJECT(argv[1])); + nativeDelegate->setJSAction(jsFunc); + nativeDelegate->setEventType(arg2); + + + Array* nativeDelegateArray = static_cast(cobj->getUserObject()); + if (nullptr == nativeDelegateArray) + { + nativeDelegateArray = new Array(); + cobj->setUserObject(nativeDelegateArray); // The reference of nativeDelegateArray is added to 2 + nativeDelegateArray->release(); // Release nativeDelegateArray to make the reference to 1 + } + + nativeDelegateArray->addObject(nativeDelegate); // The reference of nativeDelegate is added to 2 + nativeDelegate->release(); // Release nativeDelegate to make the reference to 1 + cobj->addTargetWithActionForControlEvents(nativeDelegate, cccontrol_selector(JSB_ControlButtonTarget::onEvent), arg2); + JSB_ControlButtonTarget::_jsNativeTargetMap.insert(std::make_pair(jsDelegate, nativeDelegate)); + JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; @@ -646,21 +720,34 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); - js_proxy_t *proxy; JS_GET_NATIVE_PROXY(proxy, obj); + js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSBool ok = JS_TRUE; if (argc == 3) { + Control::EventType arg2; + ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); + JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); + obj = JSVAL_TO_OBJECT(argv[0]); - JS_GET_NATIVE_PROXY(proxy, obj); - cocos2d::Object *arg0 = (cocos2d::Object *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg0); + JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); - obj = JSVAL_TO_OBJECT(argv[2]); - JS_GET_NATIVE_PROXY(proxy, obj); - cocos2d::extension::Control::EventType *arg2 = (cocos2d::extension::Control::EventType *)(proxy ? proxy->ptr : NULL); - TEST_NATIVE_OBJECT(cx, arg2); + JSB_ControlButtonTarget* nativeTargetToRemoved = nullptr; + auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(obj); + for (auto it=range.first; it!=range.second; ++it) + { + if (it->second->_jsFunc == jsFunc && arg2 == it->second->_type) + { + nativeTargetToRemoved = it->second; + JSB_ControlButtonTarget::_jsNativeTargetMap.erase(it); + break; + } + } + + cobj->removeTargetWithActionForControlEvents(nativeTargetToRemoved, cccontrol_selector(JSB_ControlButtonTarget::onEvent), arg2); + return JS_TRUE; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3); From fd3843c4e045ef36595628e4e1b015875eac0d49 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 14:49:39 +0800 Subject: [PATCH 6/9] issue #1690: [C++ Best Practice]Adding a space after 'if'. --- .../javascript/bindings/ScriptingCore.cpp | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/scripting/javascript/bindings/ScriptingCore.cpp b/scripting/javascript/bindings/ScriptingCore.cpp index b69ad854ef..33d403fdfa 100644 --- a/scripting/javascript/bindings/ScriptingCore.cpp +++ b/scripting/javascript/bindings/ScriptingCore.cpp @@ -95,10 +95,10 @@ static void executeJSFunctionFromReservedSpot(JSContext *cx, JSObject *obj, jsval func = JS_GetReservedSlot(obj, 0); - if(func == JSVAL_VOID) { return; } + if (func == JSVAL_VOID) { return; } jsval thisObj = JS_GetReservedSlot(obj, 1); JSAutoCompartment ac(cx, obj); - if(thisObj == JSVAL_VOID) { + if (thisObj == JSVAL_VOID) { JS_CallFunctionValue(cx, obj, func, 1, &dataVal, &retval); } else { assert(!JSVAL_IS_PRIMITIVE(thisObj)); @@ -174,7 +174,7 @@ void ScriptingCore::executeJSFunctionWithThisObj(jsval thisObj, jsval* vp/* = NULL*/, jsval* retVal/* = NULL*/) { - if(callback != JSVAL_VOID || thisObj != JSVAL_VOID) + if (callback != JSVAL_VOID || thisObj != JSVAL_VOID) { // Very important: The last parameter 'retVal' passed to 'JS_CallFunctionValue' should not be a NULL pointer. // If it's a NULL pointer, crash will be triggered in 'JS_CallFunctionValue'. To find out the reason of this crash is very difficult. @@ -718,11 +718,11 @@ JSBool ScriptingCore::removeRootJS(JSContext *cx, uint32_t argc, jsval *vp) void ScriptingCore::pauseSchedulesAndActions(js_proxy_t* p) { Array * arr = JSScheduleWrapper::getTargetForJSObject(p->obj); - if(! arr) return; + if (! arr) return; Node* node = (Node*)p->ptr; for(unsigned int i = 0; i < arr->count(); ++i) { - if(arr->objectAtIndex(i)) { + if (arr->objectAtIndex(i)) { node->getScheduler()->pauseTarget(arr->objectAtIndex(i)); } } @@ -732,11 +732,11 @@ void ScriptingCore::pauseSchedulesAndActions(js_proxy_t* p) void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) { Array * arr = JSScheduleWrapper::getTargetForJSObject(p->obj); - if(!arr) return; + if (!arr) return; Node* node = (Node*)p->ptr; for(unsigned int i = 0; i < arr->count(); ++i) { - if(!arr->objectAtIndex(i)) continue; + if (!arr->objectAtIndex(i)) continue; node->getScheduler()->resumeTarget(arr->objectAtIndex(i)); } } @@ -744,12 +744,12 @@ void ScriptingCore::resumeSchedulesAndActions(js_proxy_t* p) void ScriptingCore::cleanupSchedulesAndActions(js_proxy_t* p) { Array * arr = JSCallFuncWrapper::getTargetForNativeNode((Node*)p->ptr); - if(arr) { + if (arr) { arr->removeAllObjects(); } arr = JSScheduleWrapper::getTargetForJSObject(p->obj); - if(arr) { + if (arr) { Scheduler* pScheduler = Director::getInstance()->getScheduler(); Object* pObj = NULL; CCARRAY_FOREACH(arr, pObj) @@ -779,25 +779,25 @@ int ScriptingCore::handleNodeEvent(void* data) jsval retval; jsval dataVal = INT_TO_JSVAL(1); - if(action == kNodeOnEnter) + if (action == kNodeOnEnter) { executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnter", 1, &dataVal, &retval); resumeSchedulesAndActions(p); } - else if(action == kNodeOnExit) + else if (action == kNodeOnExit) { executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExit", 1, &dataVal, &retval); pauseSchedulesAndActions(p); } - else if(action == kNodeOnEnterTransitionDidFinish) + else if (action == kNodeOnEnterTransitionDidFinish) { executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onEnterTransitionDidFinish", 1, &dataVal, &retval); } - else if(action == kNodeOnExitTransitionDidStart) + else if (action == kNodeOnExitTransitionDidStart) { executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onExitTransitionDidStart", 1, &dataVal, &retval); } - else if(action == kNodeOnCleanup) { + else if (action == kNodeOnCleanup) { cleanupSchedulesAndActions(p); } @@ -851,7 +851,7 @@ int ScriptingCore::handleTouchesEvent(void* data) for(SetIterator it = pTouches->begin(); it != pTouches->end(); ++it, ++count) { jsval jsret; getJSTouchObject(this->cx_, (Touch *) *it, jsret); - if(!JS_SetElement(this->cx_, jsretArr, count, &jsret)) { + if (!JS_SetElement(this->cx_, jsretArr, count, &jsret)) { break; } } @@ -904,10 +904,10 @@ bool ScriptingCore::executeFunctionWithObjectData(Node *self, const char *name, jsval dataVal = OBJECT_TO_JSVAL(obj); executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), name, 1, &dataVal, &retval); - if(JSVAL_IS_NULL(retval)) { + if (JSVAL_IS_NULL(retval)) { return false; } - else if(JSVAL_IS_BOOLEAN(retval)) { + else if (JSVAL_IS_BOOLEAN(retval)) { return JSVAL_TO_BOOLEAN(retval); } return false; @@ -924,10 +924,10 @@ JSBool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, ui do { if (JS_HasProperty(cx, obj, name, &hasAction) && hasAction) { - if(!JS_GetProperty(cx, obj, name, &temp_retval)) { + if (!JS_GetProperty(cx, obj, name, &temp_retval)) { break; } - if(temp_retval == JSVAL_VOID) { + if (temp_retval == JSVAL_VOID) { break; } @@ -978,7 +978,7 @@ int ScriptingCore::handleKeypadEvent(void* data) js_proxy_t * p = jsb_get_native_proxy(keypadScriptData->nativeObject); - if(p){ + if (p){ switch(action){ case kTypeBackClicked: executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "backClicked"); @@ -1009,7 +1009,7 @@ int ScriptingCore::executeCustomTouchesEvent(int eventType, for(SetIterator it = pTouches->begin(); it != pTouches->end(); ++it, ++count) { jsval jsret; getJSTouchObject(this->cx_, (Touch *) *it, jsret); - if(!JS_SetElement(this->cx_, jsretArr, count, &jsret)) { + if (!JS_SetElement(this->cx_, jsretArr, count, &jsret)) { break; } } @@ -1226,7 +1226,7 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r { double num = 0.0; // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number - if( JSVAL_IS_NUMBER(*vp)) { + if ( JSVAL_IS_NUMBER(*vp)) { ok &= JS_ValueToNumber(cx, *vp, &num ); if (!ok) { break; @@ -1487,7 +1487,7 @@ jsval ccarray_to_jsval(JSContext* cx, Array *arr) Float* floatVal = NULL; Integer* intVal = NULL; - if((strVal = dynamic_cast(obj))) { + if ((strVal = dynamic_cast(obj))) { arrElement = c_string_to_jsval(cx, strVal->getCString()); } else if ((dictVal = dynamic_cast(obj))) { arrElement = ccdictionary_to_jsval(cx, dictVal); @@ -1505,7 +1505,7 @@ jsval ccarray_to_jsval(JSContext* cx, Array *arr) CCASSERT(false, "the type isn't suppored."); } } - if(!JS_SetElement(cx, jsretArr, i, &arrElement)) { + if (!JS_SetElement(cx, jsretArr, i, &arrElement)) { break; } ++i; @@ -1535,7 +1535,7 @@ jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) Float* floatVal = NULL; Integer* intVal = NULL; - if((strVal = dynamic_cast(obj))) { + if ((strVal = dynamic_cast(obj))) { dictElement = c_string_to_jsval(cx, strVal->getCString()); } else if ((dictVal = dynamic_cast(obj))) { dictElement = ccdictionary_to_jsval(cx, dictVal); @@ -1564,7 +1564,7 @@ jsval ccdictionary_to_jsval(JSContext* cx, Dictionary* dict) JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { - if(JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) + if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) { *ret = NULL; return JS_TRUE; @@ -1596,7 +1596,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, Dictionary** ret) { } JSStringWrapper keyWrapper(JSVAL_TO_STRING(key), cx); - if(!dict) { + if (!dict) { dict = Dictionary::create(); } @@ -1980,7 +1980,7 @@ JSBool jsb_set_reserved_slot(JSObject *obj, uint32_t idx, jsval value) { JSClass *klass = JS_GetClass(obj); unsigned int slots = JSCLASS_RESERVED_SLOTS(klass); - if( idx >= slots ) + if ( idx >= slots ) return JS_FALSE; JS_SetReservedSlot(obj, idx, value); @@ -1992,7 +1992,7 @@ JSBool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret) { JSClass *klass = JS_GetClass(obj); unsigned int slots = JSCLASS_RESERVED_SLOTS(klass); - if( idx >= slots ) + if ( idx >= slots ) return JS_FALSE; ret = JS_GetReservedSlot(obj, idx); @@ -2259,7 +2259,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) + if (!JS_ValueToObject( cx, vp, &jsobj ) ) return JS_FALSE; JSB_PRECONDITION( jsobj, "Not a valid JS object"); @@ -2341,7 +2341,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); JSObject *jsobjColor; - if( ! JS_ValueToObject( cx, jsr, &jsobjColor ) ) + if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) return JS_FALSE; out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); @@ -2354,7 +2354,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); JSObject *jsobjSize; - if( ! JS_ValueToObject( cx, jsr, &jsobjSize ) ) + if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) return JS_FALSE; out->_dimensions = getSizeFromJSObject(cx, jsobjSize); @@ -2367,7 +2367,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "shadowEnabled", &jsr); out->_shadow._shadowEnabled = ToBoolean(jsr); - if( out->_shadow._shadowEnabled ) + if ( out->_shadow._shadowEnabled ) { // default shadow values out->_shadow._shadowOffset = Size(5, 5); @@ -2381,7 +2381,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); JSObject *jsobjShadowOffset; - if( ! JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) + if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) return JS_FALSE; out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); } @@ -2415,7 +2415,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "strokeEnabled", &jsr); out->_stroke._strokeEnabled = ToBoolean(jsr); - if( out->_stroke._strokeEnabled ) + if ( out->_stroke._strokeEnabled ) { // default stroke values out->_stroke._strokeSize = 1; @@ -2428,7 +2428,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) JS_GetProperty(cx, jsobj, "strokeColor", &jsr); JSObject *jsobjStrokeColor; - if( ! JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) + if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) return JS_FALSE; out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); } From 10948fcef03f506df09a40a590bf75cfe9819016 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 15:00:06 +0800 Subject: [PATCH 7/9] issue #1690: [C++ Best Practice] '{' in new line. --- .../jsb_cocos2dx_extension_manual.cpp | 60 ++++++++++++------- 1 file changed, 40 insertions(+), 20 deletions(-) diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 79838de1da..95dd2c09c2 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -76,7 +76,8 @@ static JSBool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, cocos2d::extension::ScrollView* cobj = (cocos2d::extension::ScrollView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - if (argc == 1) { + if (argc == 1) + { // save the delegate JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSB_ScrollViewDelegate* nativeDelegate = new JSB_ScrollViewDelegate(); @@ -199,7 +200,8 @@ static JSBool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - if (argc == 1) { + if (argc == 1) + { // save the delegate JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSB_TableViewDelegate* nativeDelegate = new JSB_TableViewDelegate(); @@ -249,10 +251,12 @@ public: { jsval ret; bool ok = callJSDelegate(table, idx, "tableCellSizeForIndex", ret); - if (!ok) { + if (!ok) + { ok = callJSDelegate(table, "cellSizeForTable", ret); } - if (ok) { + if (ok) + { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); Size size; JSBool isSucceed = jsval_to_ccsize(cx, ret, &size); @@ -324,13 +328,17 @@ private: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* obj = _JSTableViewDataSource; - if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) { - if(!JS_GetProperty(cx, obj, jsFunctionName.c_str(), &temp_retval)) { + if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) + { + if(!JS_GetProperty(cx, obj, jsFunctionName.c_str(), &temp_retval)) + { return false; } - if(temp_retval == JSVAL_VOID) { + if(temp_retval == JSVAL_VOID) + { return false; } + JSAutoCompartment ac(cx, obj); JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), 1, &dataVal, &retVal); @@ -354,13 +362,18 @@ private: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); JSObject* obj = _JSTableViewDataSource; - if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) { - if(!JS_GetProperty(cx, obj, jsFunctionName.c_str(), &temp_retval)) { + if (JS_HasProperty(cx, obj, jsFunctionName.c_str(), &hasAction) && hasAction) + { + if(!JS_GetProperty(cx, obj, jsFunctionName.c_str(), &temp_retval)) + { return false; } - if(temp_retval == JSVAL_VOID) { + + if(temp_retval == JSVAL_VOID) + { return false; } + JSAutoCompartment ac(cx, obj); JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), 2, dataVal, &retVal); @@ -412,7 +425,8 @@ static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval { jsval *argv = JS_ARGV(cx, vp); JSBool ok = JS_TRUE; - if (argc == 3 || argc == 2) { + if (argc == 3 || argc == 2) + { JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); pNativeSource->setTableViewDataSource(JSVAL_TO_OBJECT(argv[0])); @@ -427,10 +441,13 @@ static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval jsval jsret; do { - if (ret) { + if (ret) + { js_proxy_t *proxy = js_get_or_create_proxy(cx, ret); jsret = OBJECT_TO_JSVAL(proxy->obj); - } else { + } + else + { jsret = JSVAL_NULL; } } while (0); @@ -442,7 +459,8 @@ static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval else { cocos2d::Node* arg2; - do { + do + { js_proxy_t *proxy; JSObject *tmpObj = JSVAL_TO_OBJECT(argv[2]); proxy = jsb_get_js_proxy(tmpObj); @@ -554,7 +572,8 @@ static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, js cocos2d::extension::EditBox* cobj = (cocos2d::extension::EditBox *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); - if (argc == 1) { + if (argc == 1) + { // save the delegate JSObject *jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSB_EditBoxDelegate* nativeDelegate = new JSB_EditBoxDelegate(); @@ -605,7 +624,8 @@ public: { js_proxy_t * p; JS_GET_PROXY(p, controlButton); - if (!p) { + if (!p) + { log("Failed to get proxy for control button"); return; } @@ -665,8 +685,8 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); JSBool ok = JS_TRUE; - if (argc == 3) { - + if (argc == 3) + { JSObject* jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); Control::EventType arg2; @@ -692,7 +712,6 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex nativeDelegate->setJSAction(jsFunc); nativeDelegate->setEventType(arg2); - Array* nativeDelegateArray = static_cast(cobj->getUserObject()); if (nullptr == nativeDelegateArray) { @@ -725,7 +744,8 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); JSBool ok = JS_TRUE; - if (argc == 3) { + if (argc == 3) + { Control::EventType arg2; ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); From 299562e3bedcb2db5ca24fda8ddd213896ecf684 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 15:08:12 +0800 Subject: [PATCH 8/9] issue #1690: Initializing member variables for JSB_ControlButtonTarget. --- .../javascript/bindings/jsb_cocos2dx_extension_manual.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 95dd2c09c2..890f4b9cb3 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -597,6 +597,10 @@ class JSB_ControlButtonTarget : public Object { public: JSB_ControlButtonTarget() + : _jsFunc(nullptr), + _type(Control::EventType::TOUCH_DOWN), + _jsTarget(nullptr), + _needUnroot(false) {} virtual ~JSB_ControlButtonTarget() From 28789d674d7f182dc7b561a0505ad2c86cd8d0c7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 9 Aug 2013 15:31:20 +0800 Subject: [PATCH 9/9] issue #1690: [C++ Best Practice] Adding space in for loop. --- .../javascript/bindings/jsb_cocos2dx_extension_manual.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp index 890f4b9cb3..111fc16e95 100644 --- a/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp +++ b/scripting/javascript/bindings/jsb_cocos2dx_extension_manual.cpp @@ -699,7 +699,7 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex // Check whether the target already exists. auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(jsDelegate); - for (auto it=range.first; it!=range.second; ++it) + for (auto it = range.first; it != range.second; ++it) { if (it->second->_jsFunc == jsFunc && arg2 == it->second->_type) { @@ -760,7 +760,7 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon JSB_ControlButtonTarget* nativeTargetToRemoved = nullptr; auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(obj); - for (auto it=range.first; it!=range.second; ++it) + for (auto it = range.first; it != range.second; ++it) { if (it->second->_jsFunc == jsFunc && arg2 == it->second->_type) {